Simple Program for Multiple Inheritance in C++


Multiple inheritances, there will be many base classes and there is only one derived class which derives from all the base classes. The following is the schematic representation.

Class A and Class B are the base classes and class c is the derived class. Only one class is derived from both the base classes. Have a look at the following example Here as you can see in the schematic representation, Father and Mother are the base classes and the Daughter is derived class.

Simple Program for Multiple Inheritance in C++

#include<iostream> using namespace std; class M{ protected: int m; public: void get_m(int x){ m = x; } }; class N{ protected: int n; public: void get_n(int y){ n = y; } }; class P :public M, public N{ public: void display(){ cout<<"m="<<m<<endl; cout<<"n="<<n<<endl; cout<<"m * n="<<m*n<<endl; } }; int main(){ P p; p.get_m(10); p.get_n(20); p.display(); return 0; }

Output:-

m=10
n=20
m * n=200

Explanation of the program

In this example, we can make out that the Class M and Class N are the base classes and class p is the derived class of both these classes. This is called as multiple inheritance.