views:

1735

answers:

4

If we define a abstract class which has a pure virtual destructor, why do we have to give a definition of a destructor in the abstract class?

+11  A: 

The destructor for the base class must be called when the object is destroyed, so it needs a definition.

Jesse Beder
+6  A: 

As pointed out by Jesse, inherited destructors always get called (they are called for you by the compiler with no way to override this behavior), so it stands to reason that a virtual destructor must have an implementation. So if a pure virtual destructor must have an implementation, what is the difference between a pure virtual destructor and a regular virtual destructor? If your abstract class has only the virtual destructor declared and no other pure virtual methods, making the destructor pure will prevent somebody from being able to instantiate the abstract class.

Clusterflock
+2  A: 

Only a virtual dtor can be declared as pure. But then, since you add a declaration, you must implement the body of the dtor. As already mentioned, the destructors call their parent dtor, all up to the chain of inheritance.

Nick D
+2  A: 

Because the standard says so:

12.4.7 A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined.

The reason for this is that it is called explicitly when an object of a derived class is destroyed.

See also the answers to my previous question: Under what circumstances is it advantageous to give an implementation of a pure virtual function?

Tobias
What's wrong with this answer? Or SO for that matter?
Tobias
It is not correct to say that it is called "explicitly". It was helpful that you referenced the standard, but you should edit your answer so that it is more formally correct. "explicitly" is the opposite of how destructors are normally called.
nobar