Misspelled, Missed Error
Suppose you have a virtual function in a base class B and a derived class D that overrides that function:
struct B {
virtual void func();
};
struct B: D {
void func();
};
C++ programmers assume that D::func() overrides B::func deliberately, but what if the programmer accidentally picks the name func() without noticing that D::func() overrides B::func()? The compiler can't catch such accidental misnaming errors because the code is perfectly valid, even though it means something different from what the programmer intended.
Inadvertent overriding is fairly common. It occurs, for example, in projects where class libraries that contain hundreds of virtual functions are used. Two other problems occur even more frequently in class hierarchies:
- Misspelled function names
- Parameter mismatches
Let's look at these two more closely.
Suppose you're using a library that includes the following class:
struct Base
{
virtual void some_func1();
virtual void some_func2() const;
virtual void some_func3(long);
};
You want to derive a new class that will override the three member functions of Base. Unfortunately, you end up with code that does something quite different:
struct Derived: Base
{
void sone_func1(); //misspelled name, doesn't override
void some_func2(); //cv-mismatch, hides Base::some_func2
void some_func3(long long); //parameter mismatch, hides Base::some_func3
};
Notice that none of the three member functions of Derived actually overrides the corresponding member function of Base! What went wrong?
The function sone_func1() is misspelled. Instead of overriding Base::some_func1(), the compiler assumes that the programmer simply added a new function to Derived. So, some_func2() hidesrather than overridesBase::some_func2(), because the two functions have incompatible cv-qualification.
Finally, Derived::some_func3() also hides Base::some_func3() because the parameter lists of the two functions don't match.
Recall that implicit hiding is valid in C++. Some compilers issue a warning when a member function hides a base class name, while others don't. The declaration of Derived thus compiles successfully, which makes these bugs much harder to detect, especially when an unsuspecting client uses code written by a third party.