C++ Multilevel Inheritance
Multilevel inheritance is inheritance that happens in a chain: one class inherits from a second class, which itself inherits from a third. The members flow down the whole chain, so the class at the bottom gets everything from the classes above it.
Inheritance in a chain
Imagine three classes stacked on top of each other. Class C inherits from class B, and class B inherits from class A. This means C has its own members, plus everything from B, plus everything from A. Each link in the chain passes its members further down.
A three-level chain
#include <iostream>
using namespace std;
class Animal { // top level
public:
void breathe() { cout << "Breathing...\n"; }
};
class Mammal : public Animal { // middle level
public:
void feedMilk() { cout << "Feeding milk...\n"; }
};
class Dog : public Mammal { // bottom level
public:
void bark() { cout << "Woof!\n"; }
};
int main() {
Dog d;
d.breathe(); // from Animal
d.feedMilk(); // from Mammal
d.bark(); // from Dog
return 0;
}The object d can call all three methods even though they were defined in three different classes. That is multilevel inheritance in action: the behavior accumulates as you move down the chain.
- Each derived class can add new members while keeping the inherited ones.
- The most-derived class has access to members from every ancestor above it.
- The chain can be as long as you like, though very deep chains get hard to follow.
Constructors run top to bottom
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A constructor\n"; }
};
class B : public A {
public:
B() { cout << "B constructor\n"; }
};
class C : public B {
public:
C() { cout << "C constructor\n"; }
};
int main() {
C obj; // prints A, then B, then C
return 0;
}Multilevel inheritance is great for modeling natural hierarchies, but keep it reasonable. If a chain grows too deep, it can become confusing to track where each member came from.