What is Hierarchical Inheritance in C++

Hierarchical inheritance

Hierarchical Inheritance in C++

  • As we know that Inheritance is the process of extending the properties of a class from  another class which enables software reusability
  • It’s Interesting to know that a single class can be Inherited by several classes i.e one parent for many child classes.
  •  The process where multiple classes inherit the capabilities from a single base class is called Hierarchical inheritance

Syntax to Implement Hierarchical Inheritance

The class that is acquiring the behaviors is called child class or derived class or subclass The class from which behaviors are taken is called parent class or superclass or base class
class Parent//Single Parent class
{
...;
};
class Child1: Access Parent
{
----;
//child 1 derived from the parent
};
class Child2: Access Parent
{
----;
//child 2 also derived from the same parent class
};
Here child1 and child2 are two child classes from a common Parent class

Example program demonstrating Hierarchical inheritance

#include
using namespace std;
class parent
{
  public:
  void property()
  {
      cout<<"\nProperty earned by parent";
  }
  int money=2000;
  };

class child1:public parent//child 1 extended from parent
{
  public:
  void c1_property()
  {
    cout<<"\nproperty earned by child1";
  }
};

class child2:public parent//child 2 extended from parent
{
   //child class can be empty
  //Stiill it conatins one method and variable from parent
};

main()
{
  child1 c1;
  c1.c1_property();//childs own method
  c1.property();//taken from parent
  cout<<"\nmoney got from parent:"<<c1.money;//inherited variable
  child2 c2;
  c2.property();//taken from same parent like child 1
}

Output

property earned by child1
Property earned by parent
money got from parent:2000
Property earned by parent
  • In the above example parent  class is inherited by 2 child classes child 1 and child 2
  • child1 has a total of 2 methods its own method c1_property() and inherited method property() from parent and one inherited variable m;
  • The child2 has total 1 method i.e it didn’t write its won methods. It has only one inherited method property() and 1 variable from the parent

Hence It is called hierarchal inheritance because all the inherited class have the same level of properties and capabilities from a parent class