Loading lessons...
Multiple Inheritance
Multiple Inheritance
A class normally has one base class. Multiple inheritance lets one derived class inherit from several base classes at the same time.
Inheriting from two bases
List the base classes after the colon, separated by commas:
class A {
public:
void printA() { cout << "A"; }
};
class B {
public:
void printB() { cout << "B"; }
};
class D : public A, public B {
};
- The syntax is
class D : public A, public B. - An object of
Dhas the members of bothAandB.
int main() {
D obj;
obj.printA(); // from A
obj.printB(); // from B
return 0;
}
The diamond problem
Multiple inheritance gets tricky when two base classes share a common ancestor:
class A { public: int value; };
class B : public A { };
class C : public A { };
class D : public B, public C { };
Here A appears twice inside D, once through the B branch and once through the C branch. If code refers to value, the compiler cannot tell which copy you mean. That ambiguity is the famous diamond problem.
Caveats
- Multiple inheritance gives features from several sources at once.
- Name collisions appear when both bases declare the same member.
- The diamond shape duplicates the shared ancestor.
- Virtual base classes exist to fix the diamond, but they add their own complexity.
TL;DR
- Multiple inheritance: one class inherits from several bases:
class D : public A, public B. - Use commas to separate the base classes.
- The derived class gets every member of every listed base.
- A diamond (two bases over a shared ancestor) duplicates that ancestor.
- Duplicate ancestors cause ambiguity: the diamond problem.