Avoid Casual Mistakes in Overriding a Pure Virtual Function
I propose a way to avoid casual mistakes in overriding a pure virtual
function. The detail is as follows:
(copied from my original blog post
http://tech-allen.blogspot.com/2009/03/avoid-casual-mistakes-in-overriding.html)
A subtle bug costs (but not wastes, :) me an hour this afternoon.
Here's the whole story (if you're not interested in stories, just
scroll to the end of this post to see the conclusions.:):
I have an abstract class:
class TransactionLog {
public:
virtual ~TransactionLog() {}
virtual bool IsSuccessLogged() const = 0;
...
};
And a derived concrete class:
class InMemoryTransactionLog : public TransactionLog {
public:
virtual bool IsSucessLogged() {
...
}
...
};
I tracked down a bug and found that when expecting an
InMemoryTransactionLog to be created and its pointer be passed to
constructor of another class, I actually got a NULL.
The difficulty against further tracking down is that the instantiation
point is deep embedded inside expanded macros and templates (a
template library indeed). The only clue is that the templates use
boost::is_abstract to decide if it will actually instantiate a class,
or just use a NULL instead.
OK, that's the point, the compiler thinks InMemoryTransactionLog is
abstract (and it got quickly confirmed).
Acute readers may already noticed that I've made 2 mistakes in the
above code, in class InMemoryTransactionLog:
- The overriding member function is non-const while the one in base
class is const.
- The overriding function name is misspelt to
"IsSucessLogged" (missing an "c") instead of "IsSuccessLogged"
Yes, I was causally defining a new function. If I spelled the name
correctly and forgot the "const" keyword, I would be shadowing the
original function instead of overriding it. That's exactly the
problem.
In order to be completely immune to the mistake, I propose this new
pattern (am I the first one?:):
(It requires Boost Library. In particular, Boost.TypeTraits and
Boost.StaticAssert)
When you're deriving a concrete class from an abstract one by
overriding and implementing all its pure virtual functions, just
remember to add the following code after your class definition:
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_abstract.hpp>
class ConcreteDerivedClass : public AbstractBaseClass {
...
};
BOOST_STATIC_ASSERT(!boost::is_abstract<ConcreteDerivedClass>::value);
Note that it cannot be put within the class body if
InMemoryTransactionLog, since it is still an incomplete type there and
the assertion would always fail.
Please note that GCC will emit warnings against overloaded virtual
functions with option -Woverloaded-virtual. (That only catches the
signature difference but not misspelling of function names.)
Comments are appreciated.
Regards,
Zhen
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]