๐ 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 bothFather
andMother
. - 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:
Feature | Description |
---|---|
Inheritance Type | Multiple Inheritance |
Syntax Used | class Derived : public Base1, public Base2 |
Purpose | To inherit features from multiple classes |
Example Use Case | A class that needs behaviors from different unrelated classes |
Problem to Watch Out For | Diamond problem (solved by virtual inheritance) |