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
- Base Class (
A
) → Provides a function. - Intermediate Class (
B
) → Inherits fromA
and adds a new function. - Final Derived Class (
C
) → Inherits fromB
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
- Class
Person
(Base Class) → Has theeat()
function. - Class
Developer
(Derived fromPerson
) → Adds thesleep()
function. - Class
Programmer
(Derived fromDeveloper
) → Adds thecode()
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 → InheritsPerson
and adds sleeping behavior.Programmer
class → InheritsDeveloper
and adds coding behavior.
🚀 Multilevel inheritance allows for step-by-step specialization! Let me know if you need modifications! 🚀
0 Comments