visual c++ - Constructor and Destructor in C++ -
can tell why don't add "getch()" or "system("pause")", result right in first code else in second code display lack code in part destructor
#include "iostream.h" class chucmung1 { public : chucmung1() { cout <<"chuc mung ban nam moi khang thinh vuong\n"; } ~chucmung1() { cout <<"nam tan ty\n"; } }; // first code int main() { chucmung1 object; system("pause > null"); } // second code int main() { chucmung1 object; }
in first code, result "chuc mung ban nam moi khang thinh vuong"
in second code, result "chuc mung ban nam moi khang thinh vuong nam tan ty" in case when console don't pause after display result.
can tell why don't add "getch()" or "system("pause")", result right in first code
the object
goes out of scope , destructed when main()
exits. there nothing in code sample preventing main()
exiting, object
being destroyed without delay.
else in second code display lack code in part destructor
the getch
/pause
delaying main()
exiting, , object
still in scope @ time of pause, has not been destructed yet.
if want object
destructed before pausing code, can put object
scope gets destructed earlier:
int main() { { chucmung1 object; } system("pause > null"); }
Comments
Post a Comment