Question

First time caller here. I'm new to C++ and have tried for hours to figure this one out. Sorry to ask what seems a common question. I couldn't find the answer for the life of me.

I am getting the following compile error in visual studio:

error C2259: 'Node' : cannot instantiate abstract class
due to following members:
'void Node::printValue(void)' : is abstract.

It is my understanding that this means the pure virtual function that I created has not been implemented in a child class. From everything what I can see, it has been implemented in the intNode child. What am I doing wrong here? The code is below. Thanks in advance!

In Node.h:

class Node {            
protected: 
    Node* nextNodePtr;  

public:
    Node();
    Node* getNextNodePtr(void);
    void setNextNodePtr(Node*);
    ~Node();
    virtual void printValue() = 0; 
};

class intNode : public Node {
    int nodeInteger;       
public:
    virtual void printValue()
    {
        cout << "***" << endl;
    }

    intNode(int i) 
    { 
        nodeInteger = i; 
    }
};

In Node.cpp:

void intNode::printValue() 
{
    cout << "It's an int: " << nodeInteger << endl;
}

void Node::printValue()
{
    cout << "This is just here fix compile error" << nodeInteger << endl;
}

Edit...sorry, I forgot to add this bit. The error is pointing to this section in main

int main()
{
Node* firstNode = new Node;     <---- this line is where the error points
firstNode = new intNode;
intNode* intNode = new intNode;
Was it helpful?

Solution

You are not allowed to create instances of abstract classes. The message says so, you know it, so don't do it.

int main()
{
Node* firstNode; // do not create Node instance here. 
                 // It's a compile time error and even if not,
                 // it would have been a memory leak.

firstNode = new intNode;
intNode* intNode = new intNode;

OTHER TIPS

The following statement is incorrect.

It is my understanding that this means the pure virtual function that I created has not been implemented in a child class.

The error means that void Node::printValue(void) is pure virtual (i.e. void foo() = 0) in the Node class. This makes the Node class abstract. Since you cannot instantiate abstract classes, you see the error.

Additionally, as has been mentioned in the comments, you have defined void intNode::printValue() twice. That is incorrect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top