C++ Hierarchical Inheritance Example

In this C++ Programs, we will have a look a tC++ Hierarchical Inheritance Example. In Hierarchical inheritance of C ++ all derivative classes have a common base class. The base class includes all functions common to derived classes.

As with any other inheritance, the properties of the base class are displayed based on the used visibility mode or access specifier used during the output. The Access Specifier can be private, secure, or open.

C++ Hierarchical Inheritance Example

#include <iostream> 

using namespace std;

class A //single base class

{

    public:

  int x, y;

  void getdata()

  {

        cout << "\nEnter value of x and y:\n"; cin >> x >> y;

  }

};

class B : public A //B is derived from class base

{

    public:

  void product()

  {

      cout << "\nProduct= " << x * y;

  }

};

class C : public A //C is also derived from class base

{

    public:

  void sum()

  {

        cout << "\nSum= " << x + y;

  }

};

int main()

{

    B obj1;          //object of derived class B

    C obj2;          //object of derived class C

    obj1.getdata();

    obj1.product();

    obj2.getdata();

    obj2.sum();

    return 0;

}

Output

Enter value of x and y:
5
6
Product= 30
Enter value of x and y:
7
9
Sum= 16

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart