Reputation: 607
I have such code:
#include <iostream>
using namespace std;
class X
{
int a;
public:
X()
{
cout<<"X constructor was called"<<endl;
}
X(int n)
{
cout<<"X(int) constructor was called"<<endl;
}
~X(){cout<<"X dectructor was called"<<endl;}
};
int main()
{
X x(3);
system("PAUSE");
return 0;
}
The result of this code execution is: X(int) constructor was called . But why the destructor message have not been printed?
As I understand, we create object x by calling constructor X(int) and in the end of the program this object have to be deleted, but it did not.
Upvotes: 2
Views: 550
Reputation: 3369
Try this :
int main()
{
{
X x(3);
} // Your x object is being destroyed here
system("PAUSE");
return 0;
}
It will create a local scope for X, so that you see X being destroyed.
Upvotes: 1
Reputation: 14523
Since it's allocated on stack, Destructor should be called here:
int main()
{
X x(3);
system("PAUSE");
return 0;
} // X destructor (x go out of context)
Upvotes: 3
Reputation: 55395
The destructor is run when the object goes out of scope. I'm guessing you put system("pause")
to see its message. Well no, the scope of x
didn't yet end there, it ends after return 0;
.
Run your program from the terminal and see for yourself.
Upvotes: 2
Reputation: 9071
The destructor will not be called until the object is out of scope, and that's not going to happen until you exit main.
This is why the message doesn't pop up: The console is gone by the time the object is gone.
Upvotes: 1