C++ – When to Use Final in Virtual Method Declaration

cfinal

I know that final keyword is used to prevent virtual method from being overriden by derived classes. However, I can't find any useful example when I should really use final keyword with virtual method. Even more, it feels like usage of final with virtual methods is a bad smell since it disallows programmers to extend class in future.

My question is next:

Is there any useful case when I really should use final in virtual method declaration?

Best Answer

A recap of what the final keyword does: Let's say we have base class A and derived class B. Function f() may be declared in A as virtual, meaning that class B may override it. But then class B might wish that any class which is further derived from B should not be able to override f(). That's when we need to declare f() as final in B. Without the final keyword, once we define a method as virtual, any derived class would be free to override it. The final keyword is used to put an end to this freedom.

An example of why you would need such a thing: Suppose class A defines a virtual function prepareEnvelope(), and class B overrides it and implements it as a sequence of calls to its own virtual methods stuffEnvelope(), lickEnvelope() and sealEnvelope(). Class B intends to allow derived classes to override these virtual methods to provide their own implementations, but class B does not want to allow any derived class to override prepareEnvelope() and thus change the order of stuff, lick, seal, or omit invoking one of them. So, in this case class B declares prepareEnvelope() as final.