Can Two Classes Inherit from Each Other at the Same Time?

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.

4

1 Answer

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest