Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Friday 7 June 2013

Hierarchical Inheritance And Its C++ Program

We have discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its third type, that is, Hierarchical Inheritance.

In Object Oriented Programming, the root meaning of inheritance is to establish a relationship between objects. In Inheritance, classes can inherit behavior and attributes from pre-existing classes, called Base Classes or Parent Classes.The resulting classes are known as derived classes or child classes

There are 5 types of Inheritances used in C++:

1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchial Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance

So in Hierarchical Inheritance, we have 1 Parent Class and Multiple Child Classes, as shown in the pictorial representation given on this page, Inheritance. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level. One example could be classification of accounts in a commercial bank or classification of students in a university.

In C++, such problems can be easily converted into hierarchies. The base class will include all the features that are common to the subclasses. A subclass can be constructed by inheriting the properties of the base class. A subclass can serve as a base class for the lower level classes and so on.

A derived class with hierarchical inheritance is declared as follows:

class A {.....};            // Base class
class B: public A {.....};             // B derived from A
class C: public A {.....};             // C derived from A

This process can be extended to any number of levels. Let us understand this concept by a simple C++ program:

C++ Program For Hierarchical Inheritance:

/* Double-Click To Select Code */


class polygon
  int width, height;
  void input(int x, int y)
   width = x;
   height = y;

class rectangle : public polygon
  int areaR ()
   return (width * height);

class triangle : public polygon
  int areaT ()
   return (width * height / 2);

void main ()
 rectangle rect;
 triangle tri;
 cout <<"Area of Rectangle: "<<rect.areaR()<< endl;
 cout <<"Area of Triangle: "<<tri.areaT()<< endl;

Program Output:

Hierarchical Inheritance C++ Program

Please Comment If You Liked The Post.

Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: