/* When an object is established, the constructor of the base class is called first, and then the next derived class's
constructor, and so on, until you reach the constructor of the most derived class that derives the most number of times.
In short, objects are constructed from the "bottom up" start. Because, when a constructor is initially constructed, it is always
To invoke the constructor of its base class before it starts executing its constructor body, when the direct base class constructor is called,
If there is no specific description, the default constructor for the direct base class is called. When an object is refactored, its order is reversed.
The following procedure illustrates the problem.
//-------------------------------------------------
#include <iostream>
using namespace Std;
Class Shape
{
Public
void Draw () {cout<< "Base::D Raw ()" <<ENDL;}
void Erase () {cout<< "Base::erase ()" <<ENDL;}
Shape () {Draw ();}//base class constructor, call the draw function body above
Virtual ~shape () {Erase ();} Base class destructor, call the Erase function body above
};
//-------------------------------------------------
Class Polygon:public Shape
{
Public
Polygon () {Draw ();}
void Draw () {cout<< "Polygon::D Raw ()" <<ENDL;}
void Erase () {cout<< "Polygon Erase ()" <<ENDL;}
~polygon () {Erase ();}
};
//--------------------------------------------------
Class Rectangle:public Polygon
{
Public
Rectangle () {Draw ();}
void Draw () {cout<< "Rectangle::D Raw ()" <<ENDL;}
void Erase () {cout<< "Rectangle Erase ()" <<ENDL;}
~rectangle () {Erase ();}
};
//--------------------------------------------------
Class Square:public Rectangle
{
Public
Square () {Draw ();}
void Draw () {cout<< "Square::D Raw ()" <<ENDL;}
void Erase () {cout<< "Square Erase ()" <<ENDL;}
~square () {Erase ();}
};
//--------------------------------------------------
int main ()
{
Polygon C;
Rectangle s;
Square T;
cout<< "------------------------------------------" <<endl;
return 0;
}
//------------------------------------------
Operation Result:
Base::D Raw ()
Polygon::D Raw ()
Base::d Raw ()
Polygon::D Raw ()
Rectangle::D Raw ()
Base::d Raw ()
Polygon::D Raw ()
Rectangle::D Raw ()
Square::D Raw ()
------------------------------------------
Square Erase ()
Rectangle Erase ()
Polygon Erase ()
Base::erase ()
Rectangle Erase ()
Polygon Erase ()
Base::erase ()
Polygon Erase ()
Base::erase ()
Press any key to continue
Example of constructor and destructor invocation order in C + + class inheritance