#include <iostream>
using namespace std;
class Tester {
public:
Tester(int x);
~Tester();
int who;
} Tester_g_1(1) , Tester_g_2(2);
Tester::Tester(int id) {
cout << "Intializing" << id << endl ;
who = id;
}
Tester::~Tester() {
cout << "Destroying" << who << endl;
}
int main() {
Tester localObj(3);
cout << "This is not the first line to be displayed";
system("pause");
return 0;
}
The output that i get is:
Intializing1
Intializing2
Intializing3
This is not the first line to be displayedPress any key to continue . . .
Why does the statement in destructor dodes not work?
In use :
Compiler – microsoft visual c++ 2010 Express
OS – Win7
localObjis destructed when themainterminates (because its it’s scope), which happens after thesystem("pause"). You press a key, the destructor runs but immediately the window closes, so you don’t see it.To see the text of the destructor, you have to run the program from the command line, or use the “Start program without debugging” item from the Run menu (IIRC the VS menus) (the hotkey for it is Ctrl+F5 – thanks @Cody Gray). This adds a “Press any key to continue” after the executable has terminated, so you’ll be able to see the text wrote by the destructor.
Another way to see the destructor run can be enclosing the variable in a smaller scope, which you can do easily like this:
By the way,
system("pause")is ugly and non-portable; you should avoid it.