tommyk
tommyk

Reputation: 3307

Final non-polymorphic class in C++11

I just one to make sure no one will derive from my non-polymorphic class, so I used following syntax:

class Foo final
{
    Foo();
    ~Foo(); // not virtual

    void bar();
};

In The C++ programming language I read that final can be used together with override for classes containing virtual member functions. I tried my code sample in VS 2013 and it compiles without any warning.

Is it allowed to use keyword final for non-polymorphic classes to prevent derivation from the class ? Does the keyword override make sense with non-polymorphic classes ?

Upvotes: 3

Views: 323

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

The C++ grammar allows final to appear in two different places. One is a class-virt-specifier which can appear after the class name in a class declaration, which is how you've used it. Despite the name, using a class-virt-specifer has nothing to do with virtual functions and is allowed in non-polymorphic classes.

The other place it can be used is a virt-specifier on a member function. If present, a virt-specifer sequence consists of one or both of final and override, but is only allowed on virtual functions (9.2 [class.mem] "A virt-specifier-seq shall contain at most one of each virt-specifier. A virt-specifier-seq shall appear only in the declaration of a virtual member function (10.3)."). So override can only be used on virtual functions, so cannot be used in non-polymorphic types.

Upvotes: 4

dau_sama
dau_sama

Reputation: 4357

yes it is allowed even if your class is not virtual:

from cppreference: http://en.cppreference.com/w/cpp/language/final

When used in a class definition, final specifies that this class may not appear in the base-specifier-list of another class definition (in other words, cannot be derived from).

The override keyword on the other hand makes no sense for non polymorphic classes.

Upvotes: 1

Related Questions