Final specifier in C++11

Except of override specifier, which helps with detecting not-really-overriding methods, C++11 introduces also another specifier helpful for working with inheritance: final specifier. This one can be included to function declaration or a class definition when you want to make sure that this method will not be overriden or the class will not be used as a base class.

Usage of final method

Usage is very simple. Just add the specifier after method declaration.

class Base
{
    virtual void method() final;
};

class Derived : public Base
{
    void method(); // error!
};

Compiler will report an error, because it’s illegal to override final functions.

When to use it?

The introduction of final method into C++11 raises some questions. If somebody doesn’t want to allow to override one function, why did he make it virtual? Wouldn’t be better just to remove virtual keyword from the function in the most base class?

Imagine a base class with some virtual methods you want to override. You do so in class Derived; and from this point, the method should not be overriden in any other class. With final method you can prevent the method from overriding starting with any class in hierarchy. It is shown in following example:

class Base
{
    virtual void method();
};

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

class SecondDerived : public Derived
{
    void method(); // error!
};

The mechanism can be also used by optimization. Calling a virtual function is slower than calling not-virtual function. You can use final method to achieve devirtualization – if you call virtual method from the static object that defined this method as final, the compiler can devirtualize the call and the call has performance of not-virtual method call.

Usage of final class

When a class is not designed to be a base class, add final specifier after its name:

class NotBase final
{
};

class Derived : public NotBase // error!
{
};

When it’s useful?

Some classes are not intented to be inherited from, like std::vector or std::list, classes without virtual destructor or platform dependent classes.

Summary

Final specifier is designed for quite specific scenarios. For sure you will not see it very often in the code – the usage is just very particular, in opposite to his sibling override, which should be used wherever possible.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s