Implement a C++ program to demonstrate hierarchical inheritance
🔷 Implementing Hierarchical Inheritance in C++
Object-oriented programming is built around the concept of classes and inheritance. Hierarchical inheritance is one of the four major types of inheritance in C++, which plays a crucial role in building structured, reusable, and scalable code.
✅ What is Hierarchical Inheritance?
In hierarchical inheritance, multiple derived classes inherit from a single base class. It is like a parent (base class) with several children (derived classes).
Diagrammatically:
Base Class
/ \
Derived1 Derived2
Each derived class can inherit the properties and behaviors (members and functions) of the same base class independently.
🧠 Why Use Hierarchical Inheritance?
- To model different types of entities that share common traits.
- Promotes code reusability.
- Reduces redundancy in defining common functionality.
Example:
A base class `Animal` might have derived classes like `Dog`, `Cat`, and `Cow`, all of which share basic properties such as age and sound, but each implements specific behaviors differently.
🧑💻 C++ Program to Demonstrate Hierarchical Inheritance
Let’s implement an example using:
- `Animal` → Base class
- `Dog`, `Cat`, and `Cow` → Derived classes from `Animal`
#include <iostream>
using namespace std;
// Base Class
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
// Derived Class 1
class Dog : public Animal {
public:
void bark() {
cout << "The dog barks." << endl;
}
};
// Derived Class 2
class Cat : public Animal {
public:
void meow() {
cout << "The cat meows." << endl;
}
};
// Derived Class 3
class Cow : public Animal {
public:
void moo() {
cout << "The cow moos." << endl;
}
};
int main() {
Dog d;
Cat c;
Cow w;
cout << "Dog behavior:" << endl;
d.eat();
d.bark();
cout << "\nCat behavior:" << endl;
c.eat();
c.meow();
cout << "\nCow behavior:" << endl;
w.eat();
w.moo();
return 0;
}
🖨️ Output
Dog behavior:
This animal eats food.
The dog barks.
Cat behavior:
This animal eats food.
The cat meows.
Cow behavior:
This animal eats food.
The cow moos.
📝 Explanation
- The base class `Animal` contains a method `eat()` which is shared across all animals.
- Derived classes `Dog`, `Cat`, and `Cow` inherit `eat()` and also define their own unique methods (`bark()`, `meow()`, `moo()`).
- This shows how common behavior (eating) is reused while still allowing specialized behavior in each subclass.
🎯 Conclusion
Hierarchical inheritance is ideal when multiple classes share a common base but require individual specializations. It leads to cleaner, more maintainable code and makes programs more modular. Understanding and implementing this inheritance type equips developers to better design scalable C++ applications.
Comments
Post a Comment