In fulfilling my programming assignments, I seem to stumble on the basic C ++ concepts. I found an error in my program, and this was caused by the fact that my destructor works more times than I expected. Here is a sample code demonstrating what I'm doing wrong, down to simple things.
What I expect will be A foo(7);
allocates stack space for an object A
named foo
and calls the constructor, passing 7
. It assigns 7
number
and displays a result indicating that the constructor has run. Now B bar(foo);
allocates stack space for an object B
named bar
and calls the constructor, passing foo
by value, which is just a container for int
. The constructor assigns the parameter A
, passed to it, to its private data member A
and displays the result.
Now, when bar
goes out of scope in a closing brace, I expect the bar
destructor to be called, which displays the result on the screen and then calls the destructor for its data members, namely A a
. This destructor displays the output and discards the int number
that it contained.
The result is expected to be as follows:
A constructed with number 7. B constructor run. B destructor run. A destructed with number 7. //Destructors should be called in the reverse order of their construction right?
Actual conclusion:
A constructed with number 7. B constructor run. A destructed with number 7. //This is unexpected. B destructor run. A destructed with number 7.
What causes additional destruction?
source share