Destructor confusion

Apparently the following program is meant to give the output:


10 10
Destructing...
Destructing...

But i'm only getting the 10 10 part. Can someone explain why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// A simple constructor and destructor.

#include <iostream>

class MyClass {
      public:
          int x;
          
          // Declare constructor and destructor.
          MyClass(); // constructor
          ~MyClass(); // destructor   
};

// Implement MyClass construct.
MyClass::MyClass() {
   x = 10;
}

// Implement MyClass destructor.
MyClass::~MyClass() {
   std::cout << "Destructing...\n";
}

int main()
{
    MyClass ob1, ob2;
    
    std::cout << ob1.x << " " << ob2.x << "\n";
    
    std::cin.get();
    return 0;
}


Thanks.
Last edited on
It could be that your program exits before the destructors are actually called, e.g. the objects are destructed AFTER your return 0;, not any time before.
Hmmm odd, I hate it when examples like these come from books because you can't tell if its something your doing that's wrong or if it's the author.
you actually are getting the desired output. But like firedraco said, the dtors are called after the return -- so your cin.get() line is stalling your program before the dtors are called.

if you remove the cin.get line and run your program from the command prompt (or get your IDE to keep the console open after the program exits), you will see output as expected.
Is it possible that the program prints 10 10 then waits and when you give it input it prints the rest then terminates the console before you see the output?
Ahh yes I just compiled in VC++ as oppose to dev-C++ and it worked properly, thank you Disch!
Topic archived. No new replies allowed.