Suppose you are given the C++ code below. What would be printed out – and in what order? You will have to be aware of the execution order of the constructor and destructor in inheritance.

class Base
{
  public:

  Base ( )
  {
    cout << "Inside Base constructor" << endl;
  } 

  
  ~Base ( )
  {
    cout << "Inside Base destructor" << endl;
  } 

};

class Derived : public Base
{

  public:

  Derived  ( )
  {
    cout << "Inside Derived constructor" << endl;
  } 

  ~Derived ( )
  {
    cout << "Inside Derived destructor" << endl;
  } 

};

void main( )
{
  Derived x;
}


The question asks us to find out what will be printed out in the program above, and in what order. Basically, it's a test to see if you know in what order the constructors and destructors will be called when a program deals with inheritance.

Base class constructors and derived class destructors are called first




In the code above, when the object "x" is created, first the Base class constructor is called, and after that the Derived class constructor is called. Because the Derived class inherits from the Base class, both the Base class and Derived class constructors will be called when a Derived class object is created.

When the main function is finished running, the object x's destructor will get called first, and after that the Base class destructor will be called.

So, here is what the output of the code above would look like:

Inside Base constructor
Inside Derived constructor
Inside Derived destructor
Inside Base destructor

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.