Hierarchical Inheritance is a type of inheritance in which multiple child classes inherit from a single parent class.
Example: Hierarchical Inheritance in C++
📌 In this program:
- A Base class (
Animal
) is created with a common function. - Two Derived classes (
Dog
andCat
) inherit fromAnimal
. - Both child classes have their own functions along with the inherited function.
#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 << "Dog barks: Woof Woof!" << endl;
}
};
// Derived class 2
class Cat : public Animal {
public:
void meow() {
cout << "Cat meows: Meow Meow!" << endl;
}
};
int main() {
Dog myDog;
Cat myCat;
cout << "Dog's Behavior:" << endl;
myDog.eat(); // Inherited from Animal
myDog.bark(); // Dog's own function
cout << "\nCat's Behavior:" << endl;
myCat.eat(); // Inherited from Animal
myCat.meow(); // Cat's own function
return 0;
}
📌 Output
Dog's Behavior:
This animal eats food.
Dog barks: Woof Woof!
Cat's Behavior:
This animal eats food.
Cat meows: Meow Meow!
📝 Explanation
Animal
class: Contains a functioneat()
.Dog
class: Inherits fromAnimal
and addsbark()
.Cat
class: Inherits fromAnimal
and addsmeow()
.- In
main()
: Objects ofDog
andCat
can accesseat()
fromAnimal
, and their own functions.
Would you like more variations or explanations? 🚀
0 Comments