Sign in to follow this  
Fish Fishes

Override destructor

Recommended Posts

Andrew Russell    1394
If the deconstructor is non-virtual, then doing this will work:

// just so we're clear about inheritance:
class B { ~B() {/*...*/} }; // note lack of virtual
class A : public B { ~A() {/*...*/} };

// make a new A object
A* a = new A;
// delete it as a B object
delete static_cast<B*>(a);


However, please NOTE: This is a really, really, really bad, bad, bad evil thing to do. I have trouble thinking of something worse. I suggest you come up with a better design.

Share this post


Link to post
Share on other sites
SiCrane    11839
Actually Andrew Russell's example may not work as intended, even if the destructor is non-virtual. Calling delete on a pointer with a static type different from the dynamic type of the pointed to object with a non-virtual destructor has undefined behaviour. In this case, one likely result is that while only the base class' destructor will be called, the delete expression will corrupt the heap, since a deallocation of the wrong size may occur. This is especially likely to happen if the underlying memory manager uses a pooled allocation algorithm. Furthermore, the realm of undefined behaviour also includes the possiblity that the derived class destructor will be called even with the casting.

Share this post


Link to post
Share on other sites
Zahlman    1682
Why would you *want* to do this? Keep in mind that the data members of a B instance implicitly include all the members of an A instance.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this