Should C++ 'interfaces' have a virtual destructor [duplicate]

Solution 1:

You should always use a virtual destructor with interfaces. Case in point:

IAnimal* animal = new Lion();
delete animal;

Now what destructor is it going to use? Definately not the Lion's destructor because the interface doesn't know about Lion's destructor.

So, have this if your interface has no memory management:

virtual ~IAnimal(){}

Solution 2:

Check out this article by Herb Sutter

Especially this part:

For the special case of the destructor only:

Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.

This assumes that base class is an 'interface' class as it mostly should be.

Solution 3:

This depends on whether you intend to manage the lifetime of objects polymorphically, using pointers to the interface class.

If you do, then the destructor must be virtual, in order to correctly delete the objects. Deleting a base-class pointer that doesn't have a virtual destructor is invalid, and gives undefined behaviour.

If you don't, then you should enforce this by making the destructor non-virtual and protected, so only derived classes can be deleted.