Posted by: rmn on: 22/08/2009
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:
23/08/2009 at 00:15
What is wrong with just the pure virtual dtr’?
23/08/2009 at 00:18
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.