c-plus-plus
  1. c-plus-plus-hierarchical-inheritance

C++ Programs Hierarchical Inheritance

Hierarchical inheritance is a type of inheritance in which a single base class is inherited by multiple derived classes. This results in a tree-like structure with the base class at the top and the derived classes branching out below it.

Syntax

class BaseClass {
    // code
};

class DerivedClass1 : public BaseClass {
    // code
};

class DerivedClass2 : public BaseClass {
    // code
};

In the above example, the two derived classes inherit from the same base class. This creates a hierarchical inheritance structure.

Example

#include <iostream>
using namespace std;

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

// Derived class 1
class Cat : public Animal {
public:
    void meow() {
        cout << "Meow" << endl;
    }
};

// Derived class 2
class Dog : public Animal {
public:
    void bark() {
        cout << "Woof" << endl;
    }
};

int main() {
    Cat cat;
    Dog dog;

    cat.eat(); // Inherited function from base class
    cat.meow(); // Function specific to Cat class

    dog.eat(); // Inherited function from base class
    dog.bark(); // Function specific to Dog class

    return 0;
}

Output

I am eating
Meow
I am eating
Woof

Explanation

In the above example, we have a base class called "Animal" with a function called "eat". We then have two derived classes, "Cat" and "Dog", which inherit from the "Animal" class. They also have their own specific functions, "meow" and "bark" respectively.

We create objects of both derived classes and call the inherited "eat" function as well as the specific functions for each class.

Use

Hierarchical inheritance is useful when you have multiple derived classes that inherit from a single base class. It allows for code reuse and makes it easier to manage code that is related.

Important Points

  • Hierarchical inheritance is a type of inheritance in which a single base class is inherited by multiple derived classes.
  • The derived classes form a tree-like structure with the base class at the top.
  • Inherited functions can be called on objects of the derived classes.
  • Specific functions for each derived class can also be called on their respective objects.

Summary

In summary, hierarchical inheritance is a powerful tool in C++ for code reuse and organization. By creating a tree-like structure with a single base class and multiple derived classes, you can create code that is easier to manage and maintain.

Published on: