c-plus-plus
  1. c-plus-plus-multiple-inheritance

C++ Programs Multiple Inheritance

Multiple Inheritance in C++ allows a class to inherit from more than one base class. This enables a derived class to have access to the members of all the base classes.

Syntax

class Derived_class : access_mode Base_class1, access_mode Base_class2, ..., access_mode Base_classN {
   // code
};

The derived class can inherit from multiple base classes using a comma (,) separator.

Example

#include <iostream>
using namespace std;

class Base1 {
   public:
      void display1() {
         cout << "Displaying from Base1" << endl;
      }
};

class Base2 {
   public:
      void display2() {
         cout << "Displaying from Base2" << endl;
      }
};

class Derived : public Base1, public Base2 {
   public:
      void display3() {
         cout << "Displaying from Derived" << endl;
      }
};

int main() {
    Derived obj;
    obj.display1();
    obj.display2();
    obj.display3();
    return 0;
}

Output

Displaying from Base1
Displaying from Base2
Displaying from Derived

Explanation

In the above example, we have defined two base classes named "Base1" and "Base2". We also have a derived class named "Derived" which inherits from both "Base1" and "Base2". The main function creates an object of "Derived" class and calls the member functions of all classes.

Use

Multiple inheritance is useful when we want to combine functionality that is already available in different classes. By combining these classes into a derived class, we can avoid code duplication and improve code reusability.

Important Points

  • Multiple inheritance allows a derived class to have access to the members of all the base classes.
  • In case of function name conflicts, we need to use scope resolution operator to access specific base class function.
  • Using multiple inheritance can make code difficult to understand and maintain if not used appropriately.
  • Multiple inheritance may lead to diamond problem, where a derived class indirectly inherits from same base class twice.

Summary

Multiple inheritance in C++ allows a class to inherit from more than one base class, which enables a derived class to have access to the members of all the base classes. It can improve code reusability, but can be difficult to understand and maintain if overused. Careful usage can help us avoid the diamond problem and make our code more manageable.

Published on: