Quick Q: When to use virtual destructors?

Quick A: When you might delete polymorphically.

Recently on SO:

When to use virtual destructors?

Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:

class Base
{
    // some virtual methods
};

class Derived : public Base
{
    ~Derived()
    {
        // Do some important cleanup
    }
};

Here, you'll notice that I didn't declare Base's destructor to be virtual. Now, let's have a look at the following snippet:

Base *b = new Derived();
// use b
delete b; // Here's the problem!

Since Base's destructor is not virtual and b is a Base* pointing to a Derived object, delete b has undefined behaviour...

Add a Comment

Comments are closed.

Comments (2)

0 0

squelart said on Aug 13, 2019 08:05 PM:

The "Quick A" summary seems incorrect to me, and unrelated to the actual (correct) SO answer.

I.e., the Quick A should be: "When you might potentially delete an instance of a derived class through a pointer to base class."
1 0

Blog Staff said on Aug 17, 2019 09:25 AM:

Updated, thanks.