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 classA
and derived classB
. Functionf()
may be declared inA
asvirtual
, meaning that classB
may override it. But then classB
might wish that any class which is further derived fromB
should not be able to overridef()
. That's when we need to declaref()
asfinal
inB
. Without thefinal
keyword, once we define a method as virtual, any derived class would be free to override it. Thefinal
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 functionprepareEnvelope()
, and classB
overrides it and implements it as a sequence of calls to its own virtual methodsstuffEnvelope()
,lickEnvelope()
andsealEnvelope()
. ClassB
intends to allow derived classes to override these virtual methods to provide their own implementations, but classB
does not want to allow any derived class to overrideprepareEnvelope()
and thus change the order of stuff, lick, seal, or omit invoking one of them. So, in this case classB
declaresprepareEnvelope()
as final.