C++ | 'Good Classes' should have virtual destructors

I know this sounds like "Good boys should behave BLA BLA BLA" but heres why :)

When you write a class, make sure you write a virtual destructor for it. Also, when you want to subclass an existing class, make sure the parent class has a virtual destructor(s).

Pointers and references to the base class object can actually point to a derived class object. If the derived class object is deleted using the base class pointer and the destructor of the base class is virtual, the destructor chain (through all subclasses) will be called. Therefore, one should publicly inherit only from classes with virtual destructors.

Heres a bad example :

class Base {
public: ~Base() { // non virtual
// ...

class Derived: public Base { // yikes ! parent has a non virtual destructor
public: ~Derived() {
// ...

int main() {
Base * p = new Derived; //seems OK
delete p; //trouble, Derived's destructor not called

So be sure to double check this recommendation everytime you write a new class or inherit from an existing one.


Post a Comment

<< Home