0
0
CppConceptBeginner · 3 min read

Multilevel Inheritance in C++: Explanation and Example

In C++, multilevel inheritance is a type of inheritance where a class is derived from a class which is also derived from another class, forming a chain of inheritance. It allows a class to inherit properties and behaviors from multiple levels of parent classes.
⚙️

How It Works

Imagine a family tree where a child inherits traits from their parent, and that parent also inherited traits from their own parent. In multilevel inheritance, a class inherits from a parent class, which itself inherits from another class, creating a chain of inheritance.

This means the bottom class in the chain has access to members (variables and functions) of all its ancestor classes. It helps organize code by building on existing features step-by-step, like adding layers of abilities.

💻

Example

This example shows three classes: Grandparent, Parent, and Child. Parent inherits from Grandparent, and Child inherits from Parent. The Child class can use functions from both Parent and Grandparent.

cpp
#include <iostream>
using namespace std;

class Grandparent {
public:
    void greet() {
        cout << "Hello from Grandparent" << endl;
    }
};

class Parent : public Grandparent {
public:
    void greetParent() {
        cout << "Hello from Parent" << endl;
    }
};

class Child : public Parent {
public:
    void greetChild() {
        cout << "Hello from Child" << endl;
    }
};

int main() {
    Child c;
    c.greet();         // From Grandparent
    c.greetParent();   // From Parent
    c.greetChild();    // From Child
    return 0;
}
Output
Hello from Grandparent Hello from Parent Hello from Child
🎯

When to Use

Use multilevel inheritance when you want to build classes that extend features step-by-step, like a chain of improvements. For example, in a game, you might have a base Character class, then a Player class that adds player-specific features, and finally a Wizard class that adds magic abilities.

This helps keep code organized and reusable, avoiding repetition by sharing common features through the inheritance chain.

Key Points

  • Multilevel inheritance forms a chain of classes where each inherits from the previous one.
  • The most derived class has access to all members of its ancestor classes.
  • It helps organize and reuse code by building on existing classes.
  • Be careful to avoid complexity and ambiguity in deep inheritance chains.

Key Takeaways

Multilevel inheritance allows a class to inherit from a class that is itself derived from another class.
It creates a chain where the bottom class can use features from all ancestor classes.
Use it to build classes step-by-step, adding features progressively.
Keep inheritance chains simple to avoid confusion and maintenance issues.