Hierarchical inheritance

Hierarchical inheritance is a type of inheritance in C++ where multiple derived classes inherit from a single base class. This allows different subclasses to share common functionalities of the base class while implementing their unique features.

Syntax

class Base {
    // Base class members
};

class Derived1 : public Base {
    // Derived1 class members
};

class Derived2 : public Base {
    // Derived2 class members
};

Example

#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "Eating..." << endl;
    }
};

class Dog : public Animal {
public:
    void bark() {
        cout << "Barking..." << endl;
    }
};

class Cat : public Animal {
public:
    void meow() {
        cout << "Meowing..." << endl;
    }
};

int main() {
    Dog myDog;
    Cat myCat;

    myDog.eat();  // Inherited from Animal
    myDog.bark(); // Specific to Dog

    myCat.eat();  // Inherited from Animal
    myCat.meow(); // Specific to Cat

    return 0;
}

Key Points

  1. Shared Base Class: Multiple derived classes inherit common functionality from a single base class.
  2. Specialization: Each derived class can have unique features while sharing common behaviors.

Example of Hierarchical Inheritance Usage

#include <iostream>
using namespace std;

class Shape {
public:
    void draw() {
        cout << "Drawing shape..." << endl;
    }
};

class Circle : public Shape {
public:
    void drawCircle() {
        cout << "Drawing circle..." << endl;
    }
};

class Square : public Shape {
public:
    void drawSquare() {
        cout << "Drawing square..." << endl;
    }
};

int main() {
    Circle circle;
    Square square;

    circle.draw();       // Inherited from Shape
    circle.drawCircle(); // Specific to Circle

    square.draw();       // Inherited from Shape
    square.drawSquare(); // Specific to Square

    return 0;
}