Hierarchical Inheritance in C++

 


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 and Cat) inherit from Animal.
  • 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 function eat().
  • Dog class: Inherits from Animal and adds bark().
  • Cat class: Inherits from Animal and adds meow().
  • In main(): Objects of Dog and Cat can access eat() from Animal, and their own functions.

Would you like more variations or explanations? 🚀

Post a Comment

0 Comments