In multiple inheritance, more than one base classes are derived from one sub class. Hence a class can inherit characteristics and features from more than one parent class.
Very few languages support multiple inheritance. C++ is one of them.
Syntax of Multiple inheritance in C++
1 2 3 4 5 6 7 8 9 10 11 | class Base1 { //Statements }; class Base1 { //Statements }; class Derive : public Base1, public Base2 { //Statements }; |
Note: Constructors are executed in the same order in which their’s class has been inherited. For e.g in above syntax, Base1 class constructor will be called first then Base2 class constructor.
Example of Multiple Inheritance in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <iostream> using namespace std; class Base1 { public: int x; Base1 (){ x = 1; cout << "Base1 Class Constructor Called \n"; } }; class Base2 { public: int y; Base2 (){ y=2; cout << "Base2 Class Constructor Called \n"; } }; class Derive : public Base1, public Base2 { public: int z; Derive(){ z = x + y; //X & y will be inherited from Base1 & Base2 cout << "Derive Class Constructor Called \n"; } void display(){ cout << "Value of z: "<<z<<endl; } }; int main() { Derive derive; derive.display(); //To display value of z return 0; } |
Output of Program
Notice we haven’t declared x and y in Derive class still, our program had run without any error because, in our C++ program, we have inherited Base1 and Base2 class into Derive class, therefore we are able to use x of Base1 and y of Base2 in Derive to calculate z.
If you have any doubt’s or didn’t understand any part of the program then do comment below.