Constructors-Destructors Calling Order
Constructors are called when objects are declared. Destructors are called in
reverse order when objects are destroyed.
Global objects' constructors are called before entering main().
No assumptions can be made about when the constructors of objects shared
between files are called.
In the following example, three objects are created of class
AClass. When the program exits the
objects’ destructors are called. A message is printed every time construction
and destruction take place.
Example
#include <iostream>
using namespace std;
class AClass
{
int a;
public:
AClass(int x) // constructor
{
a = x;
cout << a << "\'s Constructor called" << endl;
}
~AClass() // destructor
{
cout << a << "\'s Destructor Called" << endl;
}
};
AClass obj1(1);
int main()
{
AClass obj2(10);
AClass obj3(100);
}
Output
1's Constructor called
10's Constructor called
100's Constructor called
100's Destructor called
10's Destructor called
1's Destructor called
As you can see, first are called the global object's constructors,
then all the others.
The destructors are called in reverse order. Global object's destructors are
called last.