c++overridingfinalvirtual-functions

Does final imply override?


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?


Solution

  • final and override are independent requirements on either derived or base classes, respectively. Being final does not require the class/member to derive or override anything in the first place. Just be fully explicit with them (as appropriate).

    There is one inconspicuous edge case where final is used without virtual. Consider

            void f()          final;  // (1)
            void f() override final;  // (2)
    virtual void f() override final;  // (3)
    
    virtual void f()          final;  // (4)
    

    For (1), final always requires a virtual function, and for f to be implicitly virtual, it must be overriding a virtual base class function. Hence (1) and (3) are equivalent.

    (2) obviously implies virtual so it is also equivalent to (1)/(3).

    (4), however, is not equivalent to any of the above. It simply does not require a virtual base class version of f for the reasons that (1) does. (Which would also be pointless, if it did not have one.)

    So your question as to where override matters specifically: when you mark the function virtual explicitly. Which you always should, for clarity. Hence (3) is the preferable style.