mercredi 27 avril 2016

Does C++ final imply final in all aspects?

C++11 added final.

Finally!

I understand final does two things:

  • Makes a class non-inheritable.
  • Makes (virtual) functions in a class non-overridable (in a derived class).

Both of these seem independent of each other. But take for example the following:

class Foo
{
    public:
    virtual void bar()
    {
        //do something unimportant.
    }
};
class Baz final : public Foo
{
    public:
    void bar() /*final*/ override
    {
        //do something more important than Foo's bar.
    }
};

From above, I believe Baz being final should NOT need to specify that its virtual member function bar is also final. Since Baz cannot be inherited, the question of overriding bar goes out of scope. However my compiler VC++ 2015, is very quiet about this. I have not tested this on any others at the moment.

I would be glad if someone could shed some light on this topic. A quote from the standard (if any) would be extremely appreciated. Also please state any corner cases that I am unaware of, that may cause my logical belief to fail.

So, my question is: Does a final implicitly imply its virtual functions to be final as well? Should it? Please clarify.


The reason I am asking this is because final functions become qualified for de-virtualization, which is a great optimization. Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire