4

Execution order of constructor and destructor in inheritance

 2 years ago
source link: https://www.programmerinterview.com/c-cplusplus/execution-order-of-constructor-and-destructor-in-inheritance/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Execution order of constructor and destructor in inheritance

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK