Search code examples
c++abstract-classpure-virtual

Cannot instantiate abstract class, but I have


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;

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;