Multiple Inheritance

Multiple Inheritance in C++

Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes.

The constructors of inherited classes are called in the same order in which they are inherited. For example, in the following program, B’s constructor is called before A’s constructor.

 #include<iostream>
usingnamespacestd;
  
classA
{
public:
  A()  { cout << "A's constructor called"<< endl; }
};
  
classB
{
public:
  B()  { cout << "B's constructor called"<< endl; }
};
  
classC: publicB, publicA  // Note the order
{
public:
  C()  { cout << "C's constructor called"<< endl; }
};
  
intmain()
{
    C c;
    return0;
}

Output:

 B's constructor called
A's constructor called
C's constructor called

The destructors are called in reverse order of constructors.

The diamond problemThe diamond problem occurs when two superclasses of a class have a common base class. For example, in the following diagram, the TA class gets two copies of all attributes of Person class, this causes ambiguities.

For example, consider the following program.

 #include<iostream>
usingnamespacestd;
classPerson {
   // Data members of person 
public:
    Person(intx)  { cout << "Person::Person(int ) called"<< endl;   }
};
  
classFaculty : publicPerson {
   // data members of Faculty
public:
    Faculty(intx):Person(x)   {
       cout<<"Faculty::Faculty(int ) called"<< endl;
    }
};
  
classStudent : publicPerson {
   // data members of Student
public:
    Student(intx):Person(x) {
        cout<<"Student::Student(int ) called"<< endl;
    }
};
  
classTA : publicFaculty, publicStudent  {
public:
    TA(intx):Student(x), Faculty(x)   {
        cout<<"TA::TA(int ) called"<< endl;
    }
};
  
intmain()  {
    TA ta1(30);
}

Multiple Inheritance

A class can also be derived from more than one base class, using a comma-separated list:

Example

 
// Base class
class MyClass {
  public: 
    void 
    myFunction() {
      
    cout << "Some content in parent class." ;
    }
};

// 
    Another base class
class MyOtherClass {
  public: 
    void 
    myOtherFunction() {
      
    cout << "Some content in another class." ;
    }
};

// 
    Derived 
    class 
<strong>class MyChildClass: public MyClass, public MyOtherClass</strong> {
};

int main() {
  
    MyChildClass myObj;
  
    myObj.myFunction();
  myObj.myOtherFunction();
  
    return 0;
}

For more, checkout Geeks For Geeks and W3Schools.