Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I have the following base class:

class Base {
    public:
        virtual void f() {};
};

If I want to write a class that will override the f() and will not allow to override it to it's derived classes can write it using following approaches:

Approach 1:

class Derived : public Base {
    public:
        virtual void f() override final {};
};

Approach 2:

class Derived : public Base {
    public:
        void f() final {};
};

Approach 1 is a fully detailed when Approach 2 more compact and final still says that f() is actually virtual and overrides the base class method.

Which one approach is more appropriate?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
892 views
Welcome To Ask or Share your Answers For Others

1 Answer

In "Approach 1", the virtual is indeed redundant. 'override' is a special identifier that shows the reader of the code that a virtual function is being overridden, while also being a hint for the compiler to verify that it actually is. The base class has already stated that the function is virtual, so there is no need to do that again.

When not using the 'final' keyword, it is good practice to have a 'virtual', simply to maintain readability. Approach 2 is the best-practice notation in this case.

This kinda comes down to the style that is used in your environment, but final definitly does not imply override final.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...