Possible Duplicate:
Destructors for C++ Interface-like classes
Consider a simple example of a C++ abstract class, used to model an interface:
class IAnimal
{
virtual void walk()=0;
virtual ~IAnimal(){}
};
Is it better to have the destructor, or not? I don't think the destructor can be pure virtual, at least my tests give linker errors, so should an empty destructor be included?
EDIT: sorry, typo. It's a destructor not a constructor.
an empty constructor should probably be included since a typical use of an interface involves putting a pointer to some concrete object in a container, which will otherwise call the wrong destructer and will not clean the memory correctly. so if anyone is going to delete derived objects through a pointer to Ianimal make a virtual destructor, else make your destructor nonvirtual and protected. making your destructor pure virtual is probably not such a good idea, since it forces implementers of derived classes to override your destructor, eventhough they might want to do nothing
You should always use a virtual destructor with interfaces. Case in point:
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:
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.
Check out this article by Herb Sutter
Especially this part:
This assumes that base class is an 'interface' class as it mostly should be.
I think it should be a pure virtual destructor for interfaces, and all other methods are pure virtual as well.
The only reason not to make the destructor virtual would be to save the space needed for the
vptr
. As you need thevptr
anyway because you have another virtual function, I would make the destructor virtual.