Does final imply override?

后端 未结 5 1795
别跟我提以往
别跟我提以往 2021-01-31 01:28

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

5条回答
  •  再見小時候
    2021-01-31 02:02

    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.

提交回复
热议问题