Constructor-Inheritance-in-C++ .

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


Keep in your mind a constructor can inherit another construtor not a class . The derived class constructor supply the value to base class constructor . That means first the base class constructor value is initialized and then derived class constructor value is initialized .


Constructor Inheritance Demo :

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

    #include<iostream>
    using namespace std;  
    class A
    {
        int x;
        public :
         A(int a)
         {
             x=a;
             cout<<"\nA class constructor initialized";
         }
         void show_x()
         {
             cout<<"\nx="<<x;

         }

    };
    class B : public A
    {
        int a;
        public :
        B(int x,int y):A(x)
        {
            a=y;
            cout<<"\nB class constructor is initialized";
        }
        void show_a()
        {
            cout<<"\na="<<a;
        }
    };

    int main()
    {
            B obj= B(10,20);

            obj.show_x();
            obj.show_a();
            return 0;
    }
    OUTPUT : A class constructor initialized
             B class constructor initialized
             x = 10
             a = 20  
    

Welcome to AndroidATPoint.

back image                     next image