简体   繁体   中英

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.

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.

Yes! In the example you provide, the final keyword prevents any derived classes from overriding f() as you correctly say. If the function is non-virtual, D:f() is allowed to hide the base class version of the function:

struct B {
    void f() const;   // do not override
    virtual void g();
};
struct D : B {
    void f() const; // OK!
    void g();       // OK
};

By making f() a virtual and final function, any attempt at overriding or hiding causes a compile error.

Your intuition is right: making a function virtual only to immediately cap it with final has no benefit over a non-virtual function. This is just a short sample snippet to demonstrate the feature.

Additionally, as described in other answers, this actually breaks function hiding -- you won't ever be able to have an f function with the same parameter list in D or any of its derived classes.
This is a trade-off to be done when you decide to cap f in your model. Since there is no way to perform an actual virtual call here, you essentially have the disadvantage and no benefit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM