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.

  • Przemyslaw Woda

    Here we are deleting an instance of Derived via an object of Derived type, so all destructors are known.

    If main had “Base x” instead of “Derived x” a virtual destructor would need to be declared for the Derived destructor to be called

  • Ewan Rice

    I was wondering that, I’m guessing the difference is delete was called for the virtual example, where as here the program is terminating.

  • Dimos Nt

    In a previous article we had to use a virtual destructor (virtual ~Base() {…};) in order to get this exact order of execution. Now, the Base class destructor is not virtual so why it is not executed before the Derived class destructor?