The example moorecm posted is a well recognised pattern (in some circles). |
In which circles?
Sorry if this might sount bluntly, but actually I really don't know. I very very very seldom see implementations of pure virtual functions in the wild and if its almost always the destructor. But I haven't come around too much in C++ code for the past years, so maybe I missed out some very interesting pattern? ;-)
And its meaning and context are clear. Calling a helper doesn't quite convey the same meaning.
It forces the user of the class to provide an implementation (even though that implementation may be the default one). |
Can you elaborate where my version does things different? Or is the only point that the "helper function" in my example is named completely different and hence may not be associated as beeing "a default implementation of f()"?
Well, if so, I could have named it "default_f()". :-D The reasoning I provide still stands: you cannot make pure virtual default implementation protected, nor you can provide multiple versions. Both you can (or can choose not to) with the independend function.
Even another disadvantage arise with using pure virtual implementations: They are not part of the interface. Since your default implementation surely should be communicated to all users of the class (they are the one who should call it), it should be stated somewhere, hence you have to rely to comments.
1 2 3
|
struct Abstract {
virtual void f() = 0; // there IS an implementation you can use, if you like
};
|
This looks more cumbersome to me than just expressing it in code.
To get a bit more into the topic, the only real reason I see to use the default implementation of a pure virtual function instead of an protected, non-virtual replacement is: templates.
When you access the default implementation in a generic way (without ugly macros), you are bound to the symbol of the original name. You can not just generic add some "default_" before the name. (If you are with the back to the wall and a gun between your eyes, there may be some ugly techniques involving member function templates, but I better spare this one. ;)
Other than that, I don't see any advantages, only disadvantages of using the implementation of a pure virtual as default implementation.
Ciao, Imi.