user3722548
user3722548

Reputation: 17

Constructor and Destructor in C++

Can you tell why i don't add "getch()" or "system("pause")", the result is right in the first code else in the second code display to lack code in part destructor

    #include "iostream.h"
    class chucmung1
    {
     public :
         chucmung1()
         {
                    cout <<"chuc mung ban nam moi an khang thinh vuong\n";

         }
         ~chucmung1()
         {
                     cout <<"Nam Tan Ty\n";
         }


    };

  //  the first code
     int main()
     {
      chucmung1 object;
      system("pause > NULL");    
     }

  // the second code 
        int main()
     {
      chucmung1 object;
     } 

In the first code, the result is "chuc mung ban nam moi an khang thinh vuong"

In the second code, the result is "chuc mung ban nam moi an khang thinh vuong Nam Tan Ty" In this case when console don't pause after display result.

Upvotes: 0

Views: 188

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106068

The output will be identical in both cases, albeit with the destructor running after the pause in the first case, provided you don't press control-C or control-break to get out of the pause... that will terminate your program before the destructor gets a chance to run.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 595295

Can you tell why i don't add "getch()" or "system("pause")", the result is right in the first code

The object goes out of scope and is destructed when main() exits. There is nothing in that code sample that is preventing main() from exiting, thus the object is being destroyed without delay.

else in the second code display to lack code in part destructor

The getch/pause is delaying main() from exiting, and the object is still in scope at the time of the pause, so it is has not been destructed yet.

If you want the object to be destructed before pausing the code, you can put the object into another scope so it gets destructed earlier:

int main()
{
    {
        chucmung1 object;
    }
    system("pause > NULL");    
}

Upvotes: 3

Related Questions