As I understand it, the override
keyword states that a given declaration implements a base virtual
method, and the compilation should fail if there is no matching base method found.
My understanding of the final
keyword is that it tells the compiler that no class shall override this virtual
function.
So is override final
redundant? It seems to compile fine. What information does override final
convey that final
does not? What is the use case for such a combination?
final
does not require the function to override anything in the first place. Its effect is defined in [class.virtual]/4 as
If a virtual function
f
in some classB
is marked with the virt-specifierfinal
and in a classD
derived fromB
a functionD::f
overridesB::f
, the program is ill-formed.
That's it. Now override final
would simply mean
„This function overrides a base class one (override
) and cannot be overriden itself (final
).“
final
on it's own would impose a weaker requirement.
override
and final
have independent behavior.
Note that final
can only be used for virtual functions though - [class.mem]/8
A virt-specifier-seq shall appear only in the declaration of a virtual member function (10.3).
Hence the declaration
void foo() final;
Is effectively the same as
virtual void foo() final override;
Since both require foo
to override something - the second declaration by using override
, and the first one by being valid if and only if foo
is implicitly virtual, i.e. when foo
is overriding a virtual function called foo
in a base class, which makes foo
in the derived one automatically virtual. Thus override
would be superfluous in declarations where final
, but not virtual
, occurs.
Still, the latter declaration expresses the intent a lot clearer and should definitely be preferred.