In various explanations of C++11's final
keyword, I'm seeing examples like this.
class base
{
public:
virtual void f() final;
};
class derived : public base
{
public:
virtual void f(); // Illegal due to base::f() declared final.
};
Is this actually a useful use of final
? Why would you declare a virtual function in a base class (implying that it will be usefully overrideable in derived classes) and then immediately mark it as final
(negating that implication)? What is the utility of virtual void f() final
?
I can see the value of marking derived::f()
final rather than base::f()
. In this case, base::f()
presumably had a good design-based reason for why f()
should be virtual, and derived::f()
separately has a good design-based reason for why no further-derived class should override its implementation.
If you don't want the function overridden polymorphically, why not just leave off the virtual keyword? Of course, derived classes might still override the function non-polymorphically. Is the purpose of virtual void f() final
in the base class therefore to make base::f()
firmly non-overrideable in any way—either as a virtual or non-virtual function? If so, then it seems a bit unfortunate that we must add the virtual
keyword in this case only to enable use of final
. I would think that it should then be legal to mark even non-virtual functions as final.
Why use virtual void f() final
for a function originating in a base class when the sense of virtual
and the sense of final
seem to contradict?
final
means. To use a real-world example would require three: one to initiate the virtual, one to derive from it and befinal
, and a third to attempt to derive from it and overload it. This way is shorter. – Titanite