Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 335
tommyk Avatar asked Dec 19 '25 20:12

tommyk


2 Answers

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.

like image 170
Jonathan Wakely Avatar answered Dec 22 '25 12:12

Jonathan Wakely


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.

like image 36
dau_sama Avatar answered Dec 22 '25 11:12

dau_sama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!