Jump to content
  • Advertisement
Sign in to follow this  

Override destructor

This topic is 4705 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
Using C++? You don't (well, you really really really shouldn't). Chances are you can rearange your classes into a different pattern that will work better. But without knowing what A and B actually are, I can't offer any tips with regards to that, sorry.

Share this post


Link to post
Share on other sites
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
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!