Just recently learned the correct application of inheritance of classes in Java and thought to apply it to some code I’m writing in C++.
The following is a header for an empty Node.cpp:
#ifndef Node_h
#define Node_h
#include <string>
using namespace std;
///////////////////////////////////////////////////////
//Class Declarations
class Array;
class Hash;
class Node;
class BodyNode;
class RealNode;
class CharNode;
class ComboNode;
class EndNode;
class HashNode;
class NodeFollower;
///////////////////////////////////////////////////////
//Class Definitions
class Node{
public:
virtual string toString(int info) = 0;
};
class BodyNode: public Node{
public:
};
class RealNode: public BodyNode{
protected:
Hash *wordHash, *addressHash;
Array *followers;
int count;
//Initialization
RealNode();
~RealNode();
//Hashes
BodyNode getNext(int address);
NodeFollower getWord(BodyNode *word);
NodeFollower getAddress(int address);
string toString(int info);
};
#endif
From this code, I get the following error:
Node.h:43:11: error: invalid abstract return type for member function ‘BodyNode RealNode::getNext(int)’
Node.h:28:7: note: because the following virtual functions are pure within ‘BodyNode’:
Node.h:25:17: note: virtual std::string Node::toString(int)
Looked this up all over google, stackoverflow, and cplusplus, and while I find a lot of answers that surround this concern, I couldn’t find the exact answer that I needed to fix it. The cplusplus.com site that I was sourcing from is:
http://www.cplusplus.com/doc/tutorial/polymorphism/
Additionally, a few of the answers I found on stackoverflow indicated that
using namespace std;
is to be avoided, and it sounds like for good reason, but I can’t figure out how to include string. I tried
string::string
for each declaration, and I tried
using namespace std::string;
but both were to no avail. Thank you in advance for the help!
Your first problem is that BodyNode inherits from regular Node which has a
toString()pure-virtual function. If it’s pure-virtual (the =0) then you MUST provide a definition for it in all derived classes, and you have not.So, since you have not provided the pure-virtual function definition within
BodyNode, it is also an abstract class and uninstantiable (an abstract-class has 1 or more pure-virtual methods so it cannot be instantiated).You also have an issue that
getNext()returns aBodyNodetype, and sinceBodyNodeis abstract, this isn’t possible – you COULD return a pointer to it instead of a by-copy-value, but I think your real problem is that it shouldn’t be abstract in the first place.Provide a default
toString()function in BodyNode to fix your problem.