Reputation: 309
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?
Upvotes: 2
Views: 5241
Reputation: 58412
As others have said, the problem is that bi_dir_Node
doesn't have a void connect(Node* _Node)
method.
Conceptually, what's going on is that inheritance indicates an "is a" relationship. Saying that bi_dir_Node
inherits from Node
means that bi_dir_Node
is a Node
, so anything that a Node
can do, a bi_dir_Node
can do.
You're trying to say that bi_dir_Node
is a Node
but that it can't do everything a Node
can: specifically, it can't Connect
with a single argument.
The solution is to either provide a single-argument Connect
for bi_dir_Node
or to remove or redesign the inheritance structure. For example, in C++, templates may be a better approach: you can make uni_dir_Node
and bi_dir_Node
completely separate (not part of the same inheritance hierarchy) and write template classes and template functions that are generic enough to operate on both.
Upvotes: 1
Reputation: 4913
As says nwp, to have polymorphism, you need to have functions with the same prototypes in the derived classes.
By prototype, it means :
This is because all functions need to be called the same way and same semantic whether it is a base or derived object.
virtual
key word must be put on the base class method prototype.
The virtual
behavior is inherited. So it can be put or not on derived class overriden methods.
Advanced stuff - not often useful :
Since C++ 98 (prehistory !), if a base class method is
Base * Method();
The derived method can be :
Derived * Method();
This is because Derived* IS A KIND of Base*
Hope it clarifies
Upvotes: 0