Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
835 views
in Technique[技术] by (71.8m points)

c++ - Isn't 'virtual' keyword redundant when 'override' or 'final' specifiers are used?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...