Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "override/final" need to placed after function declarator?

Tags:

c++

I've always wondered about the decision, why override and final has to be after member-function declarator:

struct Base {
    virtual void virtFun();
};
struct Foo: Base {
    virtual void virtFun() override;
};

For me, it would be more logical to put override/final in place of virtual:

struct Base {
    virtual void virtFun();
};
struct Foo: Base {
    override void virtFun();
};

Is there a reason behind this? Maybe some compatibility issue with pre C++11?

like image 432
geza Avatar asked Nov 02 '17 22:11

geza


People also ask

Is override necessary in c++?

The override specifier was introduced to the language with C++11 and it is one of the easiest tool to significantly improve the maintainability of our codebases. override tells both the reader and the compiler that a given function is not simply virtual but it overrides a virtual method from its base class(es).

Why use override keyword c++?

The override keyword serves two purposes: It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class." The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

What is override final C++?

override (C++11) final (C++11) [edit] Specifies that a virtual function cannot be overridden in a derived class or that a class cannot be derived from.

Can you override without virtual C++?

Save this question.


1 Answers

It's because override and final are not keywords.

Instead they are special identifiers.

That means you can actually declare variables, functions or type-names (type-alias or classes) with those names.

They can only be used like member-function modifiers in a very small context, where the context have to be know beforehand by the compiler as it parses the source. Placing them after the function declaration is a very simple way of removing ambiguity from the C++ grammar for that context.

like image 95
Some programmer dude Avatar answered Oct 04 '22 14:10

Some programmer dude