AnthonyCalandra / modern-cpp-features

A cheatsheet of modern C++ language and library features.
MIT License
19.6k stars 2.08k forks source link

Fix definition of final specifier #70

Closed serg06 closed 4 years ago

serg06 commented 4 years ago
  1. As explained here: https://en.cppreference.com/w/cpp/language/final, final works whether a function is virtual or not.
  2. Isn't virtual final kinda redundant? Why would you allow overriding with virtual, then disallow it with final?
AnthonyCalandra commented 4 years ago
  1. EDIT: At first I agreed with you but then I did some digging around into the language, and now I think the virtual should stay. final must be coupled with a virtual member function. I think the confusion is from this code example in the page you link:
    struct Base
    {
    virtual void foo();
    };
    struct A : Base
    {
    void foo() final; // Base::foo is overridden and A::foo is the final override
    };

    foo is clearly not virtual because there is no virtual specifier -- or is it! Even though there is no virtual keyword there, it's still virtual.

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).

Source: https://en.cppreference.com/w/cpp/language/virtual

  1. Here's an example: I don't want a derived class to hide my member function f.
    struct A {
    // void f() final; <- Compiler error: needs virtual
    virtual void f() final; // OK
    };
    struct B : A {
    void f(); // Compiler error: overrides final mf
    };

    The point is maybe I want derived classes to have f as a member function without it being changed in a derived class.

serg06 commented 4 years ago

Ahh I see. Thanks for clearing it up for me.