Multiple inheritance is a type of inheritance that allows a class to inherit from more than one class. It is important to note that the constructors of the inherited classes are invoked in the same sequence in which they are inherited. Let us consider an example below:
Source Code 1
As you can see in the output, constructor of class myClass2 is called before the constructor of myClass3.
The constructors are called in the same sequence as they are inherited but destructors are called in the reverse order. For example,
Source Code 2
As you can see in the output, desctructors are called in the reverse order.
The diamond problem is a type of issue that occurs when two supeclasses have the common base class.
For example, the subclasses of myClass1 (myClass2 and myClass3) inherits from the common base class myClass4.
This problem causes ambiguities in the program. Let us consider the following program:
As you can see in the output, the constructor of myClass4 has been called twice.
On the basis of the above program, we can say that myClass1 object has two copies of all the member of myClass4 and this causes ambiguity. We can solve this problem using the concept of the virtual keyword. From myClass2 and myClass3 we can virtually inherit the myClass4 in order to avoid two copies of myClass4 member in myClass1 object. For example, consider the following program:
This time the constructor of myClass4 has been called only once.
In this article we discussed what is multiple inheritance in C++ and how we can achieve it. We have also seen the diamond problem that may arise due to multiple inheritance. We believe this article has surely helped you to gain some knowledge and strengthen the concept of OOPS using C++.