Javatpoint Logo
Javatpoint Logo

Hierarchical inheritance in C++

The concept of inheritance is very similar to the real world. Just like a son inherits the properties (characteristics and behavior) of his father and father himself inherits the properties of the son's grandfather. In programming norms, inheritance occurs when one class inherits the properties of another class(base).

Now let us understand the concept of hierarchical inheritance.

Hierarchical inheritance in C++

Definition

As the name defines, it is the hierarchy of classes. There is a single base class and multiple derived classes. Furthermore, the derived classes are also inherited by some other classes. Thus a tree-like structure is formed of hierarchy.

Hierarchical inheritance in C++

Here class A is the base class. Class B and Class C are the derived classes of A.

Class D and Class E are derived classes of B. Class F and Class G are derived classes of C. Thus forming the structure of hierarchical inheritance.

Where hierarchical inheritance does is used?

It is used in the following cases where hierarchy is to be maintained. For instance, the database of an organization is stored in the hierarchical format. There are different sections of an organization such as IT, computer science, Civil, Mechanical, etc. Each organization has the same attributes such as student name, roll number, year, etc. which comes under a class Student. Hence all the sections inherit the student properties and thus following the format of hierarchical inheritance.

Syntax

Class Parent is the base class and Derived1 and Derived2 are the class that inherit Parent class. Further, newderived1 is the class that inherits Dervied1, and newderived2 is the class that inherits the Derived2 class. There can be any number of base classes that are inherited by n number of derived classes.

Code example

Output

Hierarchical inheritance in C++

Explanation

We have class A as our base class which has two data members x and y. It also inputs the values of the data members using the function getdata(). Class B inherits class A and performs the products using the inherited data members x and y.

Class C also calls the getdata() of base and performs the product of x and y using the inherited data members.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA