fredoverflow fredoverflow - 1 year ago 70
C++ Question

What's the point of a final virtual function?

Wikipedia has the following example on the C++11 final modifier:

struct Base2 {
virtual void f() final;

struct Derived2 : Base2 {
void f(); // ill-formed because the virtual function Base2::f has been marked final

I don't understand the point of introducing a virtual function and immediately marking it as final. Is this simply a bad example, or is there more to it?

Answer Source

Typically final will not be used on the base class' definition of a virtual function. final will be used by a derived class that overrides the function in order to prevent further derived types from further overriding the function. Since the overriding function must be virtual normally it would mean that anyone could override that function in a further derived type. final allows one to specify a function which overrides another but which cannot be overridden itself.

For example if you're designing a class hierarchy and need to override a function, but you do not want to allow users of the class hierarchy to do the same, then your might mark the functions as final in your derived classes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download