I'm trying to understand an example given in my textbook. According to the answer key for the textbook, the program at the end of my post will display the following (FYI the text explaining is not part of the actual output, just notes from the answer to explain where it comes from):
4 (This line is displayed by constructor #2)
7 (This line is displayed by constructor #1)
2 (This line is displayed by constructor #2)
2 (This line is displayed by the destructor)
7 (This line is displayed by the destructor)
4 (This line is displayed by the destructor)
When I run this code in Visual Studio, I only get the following
4 (Presumably from constructor #2)
2 (Presumably from constructor #2)
Both the constructor and destructors never seem to get called. I think I understand why the destructor isn't called - I have to place a break at return 0 to keep the console terminal open, and I suspect that the object isn't destroyed until main returns 0, and so I don't see the destructor being called. If anyone can confirm this, it'd be appreciated.
Moreover, I'm stumped as to why the constructor never seems to be called so that you see an output of 7 when you create obj2. Does anyone have any thoughts as to why this is the case?
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
|
#include <iostream>
using namespace std;
class Package
{
private:
int value;
public:
Package()
{
cout << "Now triggering the constructor" << endl;
value = 7; cout << value << endl;
}
Package(int v)
{
value = v; cout << value << endl;
}
~Package()
{
cout << value << endl;
}
};
int main()
{
Package obj1(4);
Package obj2();
Package obj3(2);
return 0;
}
|