C++ Multilevel Inheritance

C++ Tutorial

🧬 C++ Multilevel Inheritance

Multilevel inheritance is a type of inheritance. In this case, a class comes from another derived class. This creates a chain of inheritance.

👉 Grandparent → Parent → Child


🔹 1. Basic Syntax

class A {
// base class
};
class B : public A {
// derived from A
};class C : public B {
// derived from B
};

🔹 2. Simple Example

class Animal {
public:
void eat() {
cout << "Eating" << endl;
}
};
class Mammal : public Animal {
public:
void walk() {
cout << “Walking” << endl;
}
};class Dog : public Mammal {
public:
void bark() {
cout << “Barking” << endl;
}
};int main() {
Dog d;
d.eat(); // from Animal
d.walk(); // from Mammal
d.bark(); // from Dog
}


🔹 3. Constructor Call Order

In multilevel inheritance, constructors are called from base to derived.

class A {
public:
A() {
cout << "A Constructor" << endl;
}
};
class B : public A {
public:
B() {
cout << “B Constructor” << endl;
}
};class C : public B {
public:
C() {
cout << “C Constructor” << endl;
}
};int main() {
C obj;
}

Output:

A Constructor
B Constructor
C Constructor

🔹 4. Destructor Call Order

Destructors are called in reverse order.

~C() → ~B() → ~A()

🔹 5. Access Specifiers in Multilevel Inheritance

class A {
protected:
int x;
};
class B : public A {
};class C : public B {
public:
void show() {
cout << x; // accessible
}
};

protected members are accessible down the inheritance chain
private members are not inherited


🔹 6. Method Overriding in Multilevel Inheritance

class A {
public:
virtual void show() {
cout << "Class A";
}
};
class B : public A {
public:
void show() {
cout << “Class B”;
}
};class C : public B {
public:
void show() {
cout << “Class C”;
}
};
A* obj;
C c;
obj = &c;
obj->show(); // Class C

✔ Runtime polymorphism works across multiple levels


🔹 7. Real-Life Example

Vehicle → Car → ElectricCar
  • Vehicle: start(), stop()

  • Car: gear(), fuel()

  • ElectricCar: battery()


🔹 8. Advantages

  • Strong code reuse

  • Logical hierarchy

  • Easier maintenance


🔹 9. Disadvantages

  • Tight coupling

  • Changes in base affect all derived classes

  • Can become complex if deep


❌ Common Mistakes

class B : private A {};

➡ Restricts access unintentionally.


📌 Summary

  • Multilevel inheritance forms a chain of classes

  • Constructors: base → derived

  • Destructors: derived → base

  • Supports method overriding & polymorphism

  • Use virtual for runtime binding

You may also like...