Multiple Inheritance in C++

Inheritance is one of the core feature of an object-oriented programming language. It allows software developers to derive a new class from the existing class. The derived class inherits the features of the base class (existing class). In this tutorial we will study and understand the concept of Multiple Inheritance in C++.

Multiple Inheritance in C++

In C++ programming, a class can be derived from more than one parents. When a class is derived from two or more base classes, such inheritance is called Multiple Inheritance. Multiple Inheritance in C++ allow us to combine the features of several existing classes into a single class.

 

Multiple Inheritance in C++

Syntax of Multiple Inheritance
class base_class1
{
properties;
methods;
};
class base_class2
{
properties;
methods;
};
... ... ...
... ... ...
class base_classN
{
properties;
methods;
};
class derived_classname : visibility_mode base_class1, visibility_mode base_class2,... ,visibility_mode base_classN
{
properties;
methods;
};
Multiple Inheritance in C++ Example Program

Run Online

#include <iostream>
using namespace std;

class Base1 {
  public:
    Base1()
    {
      cout << "This is Base 1" << endl;
    }
};

class Base2 {
  public:
    Base2()
    {
      cout << "This is Base 2" << endl;
    }
};

class Child: public Base1, public Base2 {

};

int main()
{
    Child obj;
    return 0;
}
Ambiguity in Multiple Inheritance

In multiple inheritance, a single class is derived from two or more parent classes. So, there may be a possibility that two or more parents have same named member function. If the object of child class needs to access one of the same named member function then it results in ambiguity. The compiler is confused as method of which class to call on executing the call statement. Here’s an example of such program:

class base1
{
  public:
     void someFunction( )
     { .... ... .... }  
};
class base2
{
    void someFunction( )
     { .... ... .... } 
};
class derived : public base1, public base2
{
    
};

int main()
{
    derived obj;
    obj.someFunction() // Error!  
}

This problem can be solved using scope resolution(::) function to specify which function to class either base1 or base2

int main()
{
    obj.base1::someFunction( );  // Function of base1 class is called
    obj.base2::someFunction();   // Function of base2 class is called.
}
Watch it on YouTube

Leave a Reply

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