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 inheritanceSyntax 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 classclass 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
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
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
Login/Signup to comment