Final non-polymorphic class in C ++ 11
I'm just one to make sure no one gets derived from my non-polymorphic class, so I used the following syntax:
class Foo final
{
Foo();
~Foo(); // not virtual
void bar();
};
In the C ++ programming language, I read what final
can be used together with override
for classes that contain virtual member functions. I tried my sample code in VS 2013 and it compiles without warning.
Is it allowed to use the keyword final
for non-polymorphic classes to prevent inference from the class? Does the keyword override
make sense with non-polymorphic classes?
source to share
The C ++ grammar allows you final
to appear in two different places. One is the -virt class specifier, which may appear after the class name in the class declaration as you used it. Despite the name, the use of the-virt-specificer class has nothing to do with virtual functions and is allowed in non-polymorphic classes.
Another place it can use is the virt specifier in the member function. If present, the virt pointer sequence consists of one or both final
and override
, but only allowed for virtual functions (9.2 [class.mem] ". The virt-seq specifier must contain at most one of each virt-specifier. The virt-seq specifier should only appear in the virtual member function declaration (10.3). "). Thus, it override
can only be used for virtual functions, so it cannot be used on non-polymorphic types.
source to share
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 indicates that the class may not appear in the base-list-specifier of another class definition (in other words, it cannot be derived from.)
The override keyword, on the other hand, doesn't make sense for non-polymorphic classes.
source to share