C++ puzzle – The Solution

Posted on March 29, 2007. Filed under: computer science, programming |

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.

Make a Comment

Make a Comment: ( None so far )

blockquote and a tags work here.

  •  

    March 2007
    M T W T F S S
    « Feb   Apr »
     1234
    567891011
    12131415161718
    19202122232425
    262728293031  
  • a

  • Archives

  • Blog Stats

    • 54,365 hits
  •       

    This work is licensed under a Creative Commons Attribution-No Derivative Works 3.0 Unported

    Beware however that this refers only to parts which are obviously written by me and do not have any other information about licencing. Quoted text, pictures and other content created by others is copyrighted by the corresponding authors. If you are in doubt, ask before republishing any content.

Liked it here?
Why not try sites on the blogroll...