C++ Multiple Inheritance

If a class is derived from two or more base classes then it is called multiple inheritance. In C++ multiple inheritance a derived class has more than one base class.

How does multiple inheritance differ from multilevel inheritance?

Though but multiple and multilevel sounds like same but they differ hugely in meaning. In multilevel inheritance, we have multiple parent classes whereas in in multiple inheritance we have multiple base classes.

To put it in simple words, in multilevel inheritance, a class is derived from a class which is also derived from another base class. And these levels of inheritance can be extended. On the contrary, in multiple inheritance, a class is derived from two different base classes.

For example

  • Multilevel inheritance : Inheritance of characters by a child from father and father inheriting characters from his father (grandfather)
  • Multiple inheritance : Inheritance of characters by a child from mother and father

C++ Multiple Inheritance Block Diagram

Following block diagram highlights its structure.

C++ multiple inheritance block diagram

As shown in above block diagram, class C is derived from two base classes A and B.

As in other inheritance, based on the visibility mode used or access specifier used while deriving, the properties of the base class are derived. Access specifier can be private, protected or public.

Click here to learn in detail about access specifiers and their use in inheritance

[adsense1]

C++ Multiple Inheritance Syntax

 class A
 {
   ..........
 };
 class B
 {
   ...........
  } ;
 class C : acess_specifier A,access_specifier A // derived class from A and B
 {
   ...........
 } ;

C++ Multiple Inheritance Example

Here is a simple example illustrating the concept of C++ multiple inheritance.

// multiple inheritance.cpp
#include 
using namespace std;
class A
{
 	public:
 	int x;
 	void getx()
    {
 	    cout << "enter value of x: "; cin >> x;
    }
};
class B
{
 	public:
 	int y;
 	void gety()
 	{
 	    cout << "enter value of y: "; cin >> y;
 	}
};
class C : public A, public B   //C is derived from class A and class B
{
 	public:
 	void sum()
 	{
 	    cout << "Sum = " << x + y;
 	}
};

int main()
{
 	 C obj1; //object of derived class C
 	 obj1.getx();
 	 obj1.gety();
 	 obj1.sum();
 	 return 0;
}   	//end of program

Output

enter value of x: 5
enter value of y: 4
Sum = 9

Explanation


In the above program, there are two base class A and B from which class C is inherited. Therefore, derived class C inherits all the public members of A and B and retains their visibility. Here, we have created the object obj1 of derived class C.