C++ program to illustrate the execution order of constructors and destructors

//when both the base and derived classes have constructors and destructors

#include <iostream>
using namespace std;
class Base
{
    protected:
        int x;
    public:
        Base(int a)
        {
            cout<<"From Base() constructor"<<endl;
            x=a;
        }
        ~Base()
        {
            cout<<"From Base() destructor"<<endl;
        }
};
class Derived1:public Base
{
    private:
        int y;
    public:
        Derived1(int a,int b):Base(a)
        {
            cout<<"From Derived1() constructor"<<endl;
            y=b;
        }
        void DisplayDerived1()
        {
            cout<<"x= "<<x<<" y= "<<y<<endl;
        }
        ~Derived1()
        {
            cout<<"From Derived1() destructor"<<endl;
        }
};
class Derived2:public Base
{
    private:
        int z;
    public:
        Derived2(int a,int c):Base(a)
        {
            cout<<"From Derived2() constructor"<<endl;
            z=c;
        }
        void DisplayDerived2()
        {
            cout<<"x= "<<x<<" z= "<<z<<endl;
        }
        ~Derived2()
        {
            cout<<"From Derived2() destructor"<<endl;
        }
};
int main()
{
    Derived1 d1(1,2);
    Derived2 d2(3,4);
    d1.DisplayDerived1();
    d2.DisplayDerived2();
    return 0;
}

No comments:

Post a Comment