Skip to content

Multiple inheritance

๐Ÿ“˜ What is Multiple Inheritance?

Multiple Inheritance is a feature in C++ where a single derived class inherits from more than one base class.

This means the derived class gets the properties and functionalities of all its base classes, helping in code reusability and flexible class design.


๐Ÿง  Real-Life Analogy:

Imagine a child inherits:

  • Skills from the father (like driving),
  • Discipline from the mother.

Similarly, in multiple inheritance, a class inherits from multiple classes.


๐Ÿ”ง Syntax:

class Base1 {
// members of Base1
};

class Base2 {
// members of Base2
};

class Derived : public Base1, public Base2 {
// members of Derived
};

๐Ÿงช Example: C++ Program Using Multiple Inheritance

#include <iostream>
using namespace std;

// Base class 1
class Father {
public:
void fatherSkills() {
cout << "Father: Skilled in driving." << endl;
}
};

// Base class 2
class Mother {
public:
void motherDiscipline() {
cout << "Mother: Disciplined and punctual." << endl;
}
};

// Derived class
class Child : public Father, public Mother {
public:
void childHobbies() {
cout << "Child: Loves to play football." << endl;
}
};

int main() {
Child c;
c.fatherSkills(); // Accessing Father class method
c.motherDiscipline(); // Accessing Mother class method
c.childHobbies(); // Child's own method
return 0;
}

โœ… Sample Output:

Father: Skilled in driving.  
Mother: Disciplined and punctual.
Child: Loves to play football.

๐ŸŽฏ Key Points:

  • The Child class inherits from both Father and Mother.
  • All public members of both base classes are available in the derived class.
  • This promotes reusability and modularity in object-oriented programming.

โš ๏ธ Caution: Diamond Problem

When two base classes inherit from a common base class and a derived class inherits from both of them, ambiguity may occur.

This is known as the Diamond Problem:

        A
/ \
B C
\ /
D

To solve this, C++ uses virtual inheritance.


โœ… Advantages of Multiple Inheritance:

  • Reusability: Use features of multiple classes.
  • Flexibility: Combines functionalities.
  • Extensibility: Can be extended easily.

โŒ Disadvantages:

  • Can lead to ambiguity/confusion if not used carefully.
  • Complex to manage if multiple base classes have same member names.
  • Increases code complexity in large programs.

๐Ÿ“Œ Summary:

FeatureDescription
Inheritance TypeMultiple Inheritance
Syntax Usedclass Derived : public Base1, public Base2
PurposeTo inherit features from multiple classes
Example Use CaseA class that needs behaviors from different unrelated classes
Problem to Watch Out ForDiamond problem (solved by virtual inheritance)