Skip to main content
gamedev.net
🔒 Locked

C++ virtual deconstructors

Started by Wavesonics Apr 2, 2007 at 12:46 PM 3 replies 1k views
Original Post
Wavesonics
Wavesonics
I have this class hierarchy, and when I delete a derived class object, i need that deconstructor plus all the deconstructors of the classes it inherits from to be called, does this happen implicitly or is only the deconstructor of the more derived class called?
MaulingMonkey
MaulingMonkey
During proper cleanup, yes, parent class deconstructors will be automatically called.

If you are deleteing a Derived through a Base* pointer, only the deconstructor of Base (not Derived!) will typically be called (I say typically as I believe this is undefined behavior), unless Base's deconstructor is declared virtual (which implicitly makes all derived class deconstructors virtual as well).
GenuineXP
GenuineXP
EDIT: You only need to worry about this with base class pointers to derived classes, as MaulingMonkey said. :-)

Yes, this happens automatically, but with base class pointers to derived classes only if you make sure to make your destructors virtual. For example, this is bad:

class Base{public:    ~Base() {}};class Derived{public:    ~Derived() {}};Base* ptr_derived = new Derived(); // OK, Derived is-a Base.delete ptr_derived; // NOT OK; Derived's destructor may not be called!

The solution: virtual destructors!

class Base{public:    virtual ~Base() {}};class Derived{public:    virtual ~Derived() {}};Base* ptr_derived = new Derived(); // OK, Derived is-a Base.delete ptr_derived; // OK, virtual destructors handle it!


Technically only the destructor in Base must be declared virtual and all other destructors in the hierarchy will also be virtual implicitly, but I find that it's good practice and clearer when you always declare your destructors this way.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.