Search code examples
c++c++11finalvirtual-functions

Does it make sense to add final keyword to the virtual function in a class that has no base class (is not derived)


I am reading an awesome awesome C++11 tutorial and the author provides this example while explaining the final keyword:

struct B {
    virtual void f() const final;   // do not override
    virtual void g();
};
struct D : B {
    void f() const;     // error: D::f attempts to override final B::f
    void g();       // OK
};

So does it make sense using here the final keyword? In my opinion you can just avoid using the virtual keyword here and prevent f() from being overridden.


Solution

  • If you don't mark the function as virtual and final then the child-class can still implement the function and hide the base-class function.

    By making the function virtual and final the child-class can not override or hide the function.