C++ Virtual Destructor

June 11, 2010

C++

All base classes should have a virtual destructor . If the class should be abstract (you want to prevent instantiating it) but it doesn’t happen to have any other pure virtual functions, a common technique to make the destructor pure virtual:

// file b.h

class B {

public: /*…other stuff…*/

virtual ~B() = 0; // pure virtual dtor

};

Of course, any derived class’ destructor must call the base class’ destructor, and so the destructor must still be defined (even if it’s empty):

// file b.cpp

B::~B() { /* possibly empty */ }

If this definition were not supplied, you could still derive classes from B but they could never be instantiated, which isn’t particularly useful.

Subscribe

Subscribe to our e-mail newsletter to receive updates.

No comments yet.

Leave a Reply