cplusplus.co.il

Pure virtual destructor

Posted 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:

  • 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).
Advertisements

2 Responses to "Pure virtual destructor"

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: