🔹 Multilevel Inheritance in C++

 


Multilevel inheritance is a type of inheritance in which a derived class inherits from another derived class, forming a chain of inheritance.


📌 Basic Example of Multilevel Inheritance

Let's start with a simple example demonstrating multilevel inheritance.

🚀 Approach

  1. Base Class (A) → Provides a function.
  2. Intermediate Class (B) → Inherits from A and adds a new function.
  3. Final Derived Class (C) → Inherits from B and adds another function.

🔹 C++ Code: Basic Example of Multilevel Inheritance

#include <iostream>
using namespace std;

// Base class
class A {
public:
    void showA() {
        cout << "This is Class A" << endl;
    }
};

// Derived class from A
class B : public A {
public:
    void showB() {
        cout << "This is Class B" << endl;
    }
};

// Derived class from B
class C : public B {
public:
    void showC() {
        cout << "This is Class C" << endl;
    }
};

int main() {
    C obj;
    obj.showA();  // Inherited from A
    obj.showB();  // Inherited from B
    obj.showC();  // Defined in C
    return 0;
}

🔹 Output

This is Class A
This is Class B
This is Class C

📌 Eat Sleep Code Example (Multilevel Inheritance)

Now, let's implement a real-world example using multilevel inheritance.

🚀 Approach

  1. Class Person (Base Class) → Has the eat() function.
  2. Class Developer (Derived from Person) → Adds the sleep() function.
  3. Class Programmer (Derived from Developer) → Adds the code() function.

🔹 C++ Code: Eat Sleep Code Example

#include <iostream>
using namespace std;

// Base Class
class Person {
public:
    void eat() {
        cout << "I am eating 🍕" << endl;
    }
};

// Derived Class from Person
class Developer : public Person {
public:
    void sleep() {
        cout << "I am sleeping 😴" << endl;
    }
};

// Derived Class from Developer
class Programmer : public Developer {
public:
    void code() {
        cout << "I am coding 💻" << endl;
    }
};

int main() {
    Programmer obj;
    obj.eat();    // Inherited from Person
    obj.sleep();  // Inherited from Developer
    obj.code();   // Defined in Programmer
    return 0;
}

🔹 Output

I am eating 🍕
I am sleeping 😴
I am coding 💻

📌 Explanation

  • Person class → Defines eating behavior.
  • Developer class → Inherits Person and adds sleeping behavior.
  • Programmer class → Inherits Developer and adds coding behavior.

🚀 Multilevel inheritance allows for step-by-step specialization! Let me know if you need modifications! 🚀

Post a Comment

0 Comments