Override destructor

Started by
3 comments, last by Zahlman 18 years, 9 months ago
I have class A, derived from A class B. How to call B's destructor w/out invoking A's destructor? Make A's destructor virtual or else??
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.
If the deconstructor is non-virtual, then doing this will work:

// just so we're clear about inheritance:class B { ~B() {/*...*/} }; // note lack of virtualclass A : public B { ~A() {/*...*/} };// make a new A objectA* a = new A;// delete it as a B objectdelete 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.
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.
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.

This topic is closed to new replies.

Advertisement