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 ?
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.