What is Hierarchical Inheritance in C++

Hierarchical Inheritance in C++

On this page we will discuss about Hierarchical inheritance in C++ . 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
What is Hierarchical Inheritance in C++

Syntax to Implement Hierarchical Inheritance in C++

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
Hierarchical Inheritance

Example:program demonstrating Hierarchical inheritance

Run
#include <iostream>
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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription