Pure virtual destructor
August 22nd, 2009 § 2 Comments
Sometimes you would like to create an abstract class, but there is no method you could naturally declare as pure virtual (=0) in order to achieve that (in a tag interface, for example).
In such cases the destructor may be the perfect candidate: as it should always be declared virtual if inheritance is considered, it may as well be pure virtual.
But then we have a hazard on our hands - since destructor (and constructor) invocation in inheriting classes is recursive, we will end up with a pure virtual method call - with no suitable code to execute. How do we solve this issue?
Well, c++ allows even pure virtual functions to have a body, which will be called in case of need. Observe the following piece of code:
struct A {
virtual ~A () = 0;
};
struct B : A{
~B () {}
};
// try to comment out the next line and recompile
A::~A () {}
int main () {
B b;
return 0;
}
If you tried to comment out the implementation of A’s destructor, the linker would complain about not being able to properly destruct the created B object.
This technique of giving bodies to pure virtual functions can be used in more occasions, such as:
- To make sure no pure virtual functions are being called (inside constructor when vtable isnt ready, for example) – by placing proper false asserts.
- Or for giving default implementations which you would not want the inheriting classes to get by default (but only by explicitly invoking them).
What is wrong with just the pure virtual dtr’?
If you comment out the implementation of that destructor (like the comment suggests), you will get a complaint from the linker. Why? Because when we are trying to destruct an object of class B, the constructor will have to first invoke the destructor of B and then the unfortunetly non-existing destructor of A (since destructor invocation is recursive like the construction, but in a reversed order) – and that is why we need a proper implementation of it, despite it being pure virtual.