Recently, during an interview, I was asked about the problem of memory leak in derived classes when the base class destructor is not declared virtual.
I wrote a small test to confirm my answer, but found something interesting. Obviously, if you create the Derived object via new , but save its pointer as Base* , the destructor of the derived object will not be called if the pointer is deleted (so much for my answer to the question).
I thought that the virtual or destructor of the derived class is relevant in this case, but on my system the following code shows differently:
#include <iostream>
I expected the program to output the following two lines and close normally:
Destructing: Base Destructing: Base
I get this conclusion, but right after the second line the program terminates with a segmentation error. And the message:
*** Error in `...': free(): invalid pointer: 0x00000000006020e8 ***
I changed the order of the two calls to delete , but the program always made a call to delete virtual_derived; . Can someone tell me why this is?
c ++ inheritance polymorphism destructor
Sebastian schneider
source share