Possible Duplicate:
Object destruction in C++
Suppose we have two classes, one is called Array and the other one is called MessageOnExit.
Assume the Array class has a static data member called counter.
Here are the classes:
class Array {
public:
static int counter;
Array(){counter++;}
~Array(){counter--;}
};
class MessageOnExit {
public:
~MessageOnExit(){cout << Array::counter;}
};
The following is the "main" using these classes:
// static variable definition
int Array::counter;
// global object definition
MessageOnExit message;
void main() {
Array a1, a2;
Array a3(a1);
}
The first two declarations will change counter to be 2 ensues two calls of the Empty/Default constructor
The third declaration won't change the counter because the Default copy constructor will be called.
Now when the main execution is done, the value of the static member counterwill be -1 ensues the destructors calls (after a1, a2 and a3 are desroyed), and then the message destructor will be called, printing this value (-1).
My question is how do we know the static member counter is still alive and available when the message destructor is being called.
Also if I change the static/global object/variable definition order, that is, message is defined before counter, the value remains -1.
To summarize, no matter what changes I do, when the program terminates the message destructor success to access the static member counter and I don't understand why is that. As far as I understand if the global object message is defined first its destructor will be called last and therefore the counter value won't be available for its destructor.
Thanks in advance! Guy