Multiple Inheritance in C++ [with Example]

programming

Summary: In this tutorial, we will learn what multiple inheritance is and how can we implement it in C++.

Introduction to Multiple Inheritance

When a class inherits multiple base classes it is known as multiple inheritance.

Block Diagram of Multiple inheritance in C++

Multiple inheritance allows a class to inherit characteristics and properties from more than one parent class.

Very few languages support multiple inheritance. C++ is one of them.

Syntax for Multiple Inheritance:

class Base1 {
    //Statements
};
 
class Base1 {
    //Statements
};
 
class Derive : <access_specifier> Base1, <access_specifier> Base2 {
    //Statements
};

In this syntax for the demonstration purpose, we have inherited only two classes, however, we can inherit more classes depending on the need.

When we inherit multiple classes, the constructors are executed in the order in which their class is inherited.

For example, in the above syntax, the Base1 class constructor will be called first and then the Base2 class constructor, followed by the Derived class.

C++ Example: Multiple Inheritance

Here is an example in C++ that inherits multiple classes.

#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:

Multiple Inheritance example in C++

Notice we have not declared X and Y in the derived class, our program went on without any errors.

It is because we have inherited the Base1 and Base2 classes in the Derived class, so are able to use their x and y in the same.

Conclusion

Multiple inheritance allows a class to inherit multiple classes.

It is useful to share resources when there are multiple IS A relation among the group of classes.

One thought on “Multiple Inheritance in C++ [with Example]”

Leave a Reply to nitin Cancel reply

Your email address will not be published. Required fields are marked *