![]() |
VOOZH | about |
Inheritance is a feature of Object-Oriented-programming in which a derived class (child class) inherits the property (data member and member functions) of the Base class (parent class). For example, a child inherits the traits of their parents.
In Hierarchical inheritance, more than one sub-class inherits the property of a single base class. There is one base class and multiple derived classes. Several other classes inherit the derived classes as well. Hierarchical structures thus form a tree-like structure. It is similar to that, mango and apple both are fruits; both inherit the property of fruit. Fruit will be the Base class, and mango and apple are sub-classes.
The below diagram shows, Class A is a Base class, B is a subclass inherited from class A, and C is a subclass it also inherits from class A.
Similarly, if another subclass inherits property from B class and so on then there will be a hierarchy, and a tree-like structure is formed, below is the diagram.
Here X and Y are sub-class (child class) that inherits property from class B, and M and N are sub-class (child class) that inherits property from class C. B is the parent class of X and Y, and C is the parent class of M and N. access_specifier provides the visibility mode in the class declaration. By inheriting from the base class, the derived class inherits the members of the base class.
Syntax:
Class A
{
............
};
Class B: access_specifier A
{
.........
};
Class C: access_specifier A
{
.............
};
Example 1:
calling from B: class B class A calling from C: class C class A
Explanation: In the above program A is the superclass also known as a parent class, and B and C are subclasses also known as the child class. class B and class C inherit property from class A.
Example 2:
shape is: triangle no. of sides are: 3 base is: 2 height is: 3 area of triangle: 3 shape is: square no. of sides are: 4 height is: 2 area of square: 4
Explanation: In the above code, we created three classes: shape, Triangle, and square. In this example, the shape class is a superclass. triangle and square are subclasses that inherit from the shape class. A constructor in every class is used to initialize data members. Then we created triangle and square objects and used details() to produce information for the triangle and square. Here, access modifiers are public.