Hierarchical-Inheritance-in-C++ .

In this session i have discussed hierarchical inheritance in C++ .


In hierarchical inheritance only one parent class and multiple child class .

hierarchical inheritance image

In above image the class A is a parent class . The class B , class C and class D is the child class (multiple child class of A class) .


Hierarchical Inheritance Demo :

Example : Write a program that demonstrate the hierarchical inheritance in C++

    #include<iostream>
    using namespace std;  
    class A
    {
        public :
        void sum(int x,int y)
        {
            int result = x + y;
            cout<<"\nSum : "<<result;
        }
    };
    class B : public A
    {
        public :
        void sub(int x,int y)
        {
            int result = x - y;
            cout<<"\nSub : "<<result;
        }
    };
    class C : public A
    { 
        public :
        void mul(int x,int y)
        {
            int result = x * y;
            cout<<"\nMulti : "<<result;
        }
    };
    class D : public A
    { 
        public :
        void div(int x,int y)
        {
            int result = x / y;
            cout<<"\nDiv : "<<result;
        }
    };
    int main()
    {
            B obj1 = new B();
            obj1.sum(20, 10);
            obj1.sub(20, 10);
            cout<<"\n--------";
            //-------------------------------
            C obj2=new C();
            obj2.sum(30,40);
            obj2.mul(20, 10);
            cout<<"\n--------";
            //------------------------------
            D obj3=new D();
            obj3.sum(20,10);
            obj3.div();
            cout<<"\n--------";
    }
    OUTPUT : Sum  : 30
             Sub  : 10
             ----------
             Sum  : 70
             Multi: 200
             ----------
             Sum  : 30
             Div  : 2
             ----------
    

Welcome to AndroidATPoint.

back image                     next image