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

lezebulon picture lezebulon · Jan 11, 2012 · Viewed 102.9k times · Source

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

David Rodríguez - dribeas picture David Rodríguez - dribeas · Jan 11, 2012

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!
};