9 comments

[ 3.1 ms ] story [ 23.8 ms ] thread
"To work correctly, classes with virtual methods must also have virtual destructors."

Not a good way to start the article... I immediately question the author's credibility following this statement.

Why? If they don't it is going to mess up the destruction sequence if they are ever stored and then released polymorphically, such as from a collection of pointers to classes.

What he is saying is standard C++ knowledge.

Sometimes an alternative is to make the destructor in the base class protected.
You can also use a protected non-virtual destructor in the base class to avoid to mess up the destruction sequence. But what he says is indeed the most common case.
I didn't know you could define member functions that were declared pure virtual. The more you know..
All of which is a workaround for the fact that there is no explicit way to declare a c++ class to be abstract-only.

What happens if you do have shared logic to put in the abstract base class's destructor? It can't be pure virtual, and you're back to being able to instantiate your 'abstract' base class...

What about making the constructors protected?
> All of which is a workaround for the fact that there is no explicit way to declare a c++ class to be abstract-only.

Sure you can. Just put the word "Abstract" in the class name, and then every programmer who reads that class name will know that it's abstract. What more does one need?

That approach is much clearer than resorting to tricks like a pure virtual destructor. At the end of the day it's all about communicating design.

It's exactly this kind of thing that lead me away from C++. There are far too many gotcha's and tricks you need to know to write good C++.