C++ puzzle – The Solution
The snippet in the previous post, does compile and runs , but with an exception. The output is “Beta Alpha” .
The display function passed in a copy of the parameter gamma, it did this by calling the base class copy constructor. As one hasn’t been defined, the compiler generated one, which did a shallow copy. A shallow copy copies all the bits, including the pointer to str2 , and on exiting display, gamma’s destructor was called and freed str2’s pointer. When the application exited, str2 was terminated and its destructor was called again, destroying an already destroyed pointer.
One way to fix this is to change
void display(base gamma)
to
void display(base & gamma))
So display uses str2 directly, rather than a copy and str2 is destroyed properly.




