C++ doesn't currently allow derived classes to gain much confidence that they have really overridden a base class virtual function. They can either declare their member function virtual
, to help document that it is an override, or they can just declare it normally. Either way, there is no way to tell that the member function is really overriding a virtual function. For example:
class Base {
public:
virtual void f();
virtual void g();
virtual void h( int );
};
class Derived : public Base {
public:
virtual void f();
void g();
void h();
void i();
void j();
};
If you were the author of Derived
, and Base
were provided by another party, would you know which of Derived
's functions were overrides? Every single one could be, or none may be. Essentially this is as bad as the C-preprocessor with regard to undefined macros evaluating to 0 in #if directives.
C preprocessor
#define Foo 1
#if foo
// oops, mistyped, but no error
#endif
Virtual functions
struct B {
virtual void Foo();
};
struct D : B {
virtual void foo(); // oops, mistyped, but no error
};
And no, "make Foo a pure virtual in B" is not an answer, beacuse pure virtual may not be appropriate.
The override
construct is meant to make this guarantee (or give a compilation error if it can't be made). It is used in place of virtual
in the overriding member function declaration. Its only effect is to cause a compilation error if the member function isn't actually overriding anything. With it in the language,virtual
would only be used to introduce new virtual functions, while override
would always be used when overriding a virtual function.
class Base {
public:
virtual void f();
virtual void g();
virtual void h( int );
};
class Derived : public Base {
public:
override void f(); // OK - we really are overriding a virtual func
override void g(); // OK - we really are overriding a virtual func
override void h(); // error - signature doesn't match Base::h
override void i(); // error - no virtual func matches this signature
void j(); // OK - doesn't override
};
One last case to consider, that of the base class providing new virtual functions that have the same name and signature as existing derived (non-override) functions:
class Base {
public:
virtual void f();
virtual void g();
virtual void h( int );
virtual void j();
};
class Derived : public Base {
public:
// ...
void j();
};
Does Derived::j()
override Base::j()
? The two reasonable possibilities include hiding Base::j()
, or causing a compilation diagnostic, the latter being the safest of the two (but breaking current code).
A note here: The "final
" construct that I detail would also have the same effect, with regards to validity, as override
when used on a member function.