Reputation: 69
I don't have any coding issues today, but i need some help in explaining a concept im struggling to find answers to. The question is:
Can you have class X inheriting from class Y and class Y inheriting from class X at the same time? Explain using code.
Upvotes: 2
Views: 2375
Reputation: 122268
It was already said in a comment: (public) inheritance models a "is a" relationship.
Forget about C++ for a moment and consider the abstract concept of inheritance and what it models. If A
inherits from B
then any instance of A
is a B
. Hence the set of all instances of A
is a subset of all instances of B
. If all instances of A
are instances of B
and all instances of B
are instances of A
, then no inheritance is needed to model the relation between A
and B
, because they are the exact same type.
Now C++ again. This:
struct A : B {};
struct B : A {};
Is not possible for two reasons. First, to make A
inherit from B
the definition of B
must be known, and to make B
inherit from A
the definition of A
must be known. Second, each instance of A
contains a subobject of type B
and each B
contains a subobject of type A
and every A
.... ad infinitum. It is not possible.
Upvotes: 5