Let’s suppose we have a base class which has a virtual method:
class BaseClass
{
virtual void MethodToOverride() const
{
DoSomething();
}
};
And a derived class which overrides the method (depending on the situation we can make it again virtual or not):
class DerivedClass : public BaseClass
{
void MethodToOverride() const
{
DoSomethingElse();
}
}
If we make a mistake, for example defining the MethodToOverride non const or with a wrong character, we simply define a new method, for example:
void MethodToOverride() {} // I forgot the const
void MthodToOverride() const {} // I made a typo
So this compiles fine, but causes unwanted behavior at runtime.
Is there any way to define a function as an explicit override of an existing one, so the compiler warns me if I define it wrongly? Something like (I know it does not exist):
void MethodToOverride() const overrides BaseClass::MethodToOverride() const {}
C++0x offers an attribute for this (see vitaut’s answer), and e.g. Visual C++ offers a language extension.
But in portable C++98 the best you can do is a sanity check, that the base class offers an accessible member function that accepts the same arguments, like …
where
You call the macro in your override implementation, with the function’s actual arguments.
EDIT Added call example (disclaimer: untouched by compiler’s hands):
Using such a sanity check can improve the clarity of the code in certain cases, and can save your ass in certain cases. It has three costs. (1) Someone Else might mistake it for a guarantee, rather than just an informative comment and partial check. (2) the member function can’t be private in the base class, as it is in your example (although that’s perhaps positive). (3) Some people react instinctively negatively to any use of macros (they’ve just memorized a rule about badness without understanding it).
Cheers & hth.,