Recently, I am learning Inheritance and Polymorphism in C++.
I made three classes: Node, uni_dir_Node(uni-direction Node), and bi_dir_Node(bi-direction Node).
Here is my code:
class Node {
protected:
string name;
Node* next;
virtual void connect(Node* _Node) = 0;
};
class uni_dir_Node : public Node {
void connect(Node* _Node) {
this->next = next;
}
};
class bi_dir_Node : public Node {
Node* previous;
void connect(Node* next_Node, Node* previous_Node) {
this->next = next;
this->previous = previous_Node;
}
};
int main()
{
Node* head = new bi_dir_Node;
return 0;
}
Of course there is a compiler error in this code.
My question is, the function connect() in class uni_dir_Node has one parameter but for the function connect() in class bi_dir_Node has two parameters. How do I keep this inheritance structure and make it legal?
Is there any good way to solve this problem?
Nodeis constructable with aNode *. Abi_dir_Nodeis not. Therefore abi_dir_Nodecannot be aNode. You can add a constructor forbi_dir_Nodethat takes a singleNode *and sets the otherNode *tonullptror makesprevious = next = node, but that is just asking for trouble. Your problem is just not suitable for inheritance and you shouldn't force it.connect()with only one argument, or fully reschedule the inheritance.