Does final imply override?

quant picture quant · Apr 2, 2015 · Viewed 18k times · Source

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?

Answer

Columbo picture Columbo · Apr 2, 2015

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 class B is marked with the virt-specifier final and in a class D derived from B a function D::f overrides B::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.