Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 672
Mr. Boy Avatar asked Sep 02 '10 15:09

Mr. Boy


People also ask

Should interfaces have virtual destructor?

Every interface class should have a virtual destructor. Virtual destructor makes sure that when a shape is deleted polymorphically, correct destructor of the derived class is invoked. Otherwise there is a good chance of resource leak.

When should destructor be virtual?

In particular, here's when you need to make your destructor virtual: if someone will derive from your class, and if someone will say new Derived, where Derived is derived from your class, and if someone will say delete p, where the actual object's type is Derived but the pointer p's type is your class.

Why do we need virtual destructor?

Virtual destructors in C++ are used to avoid memory leaks especially when your class contains unmanaged code, i.e., contains pointers or object handles to files, databases or other external objects. A destructor can be virtual.

Does a pure virtual class need a destructor?

While defining (providing an implementation) pure virtual methods is rarely useful, you must define a pure virtual destructor. This is because the destructor of a base class is always called when a derived object is destroyed.


1 Answers

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(){} 
like image 53
wheaties Avatar answered Sep 17 '22 09:09

wheaties