lezebulon lezebulon - 3 months ago 20
C++ Question

What is the purpose of the "final" keyword in C++11 for functions?

What is the purpose of the

final
keyword in C++11 for functions? I understand it prevents function overriding by derived classes, but if this is the case, then isn't it enough to declare as non-virtual your
final
functions? Is there another thing I'm missing here?

Answer

What you are missing, as idljarn already mentioned in a comment is that if you are overriding a function from a base class, then you cannot possibly mark it as non-virtual:

struct base {
   virtual void f();
};
struct derived : base {
   void f() final;       // virtual as it overrides base::f
};
struct mostderived : derived {
   //void f();           // error: cannot override!
};