final
keyword specifies that a virtual function cannot be overridden in a derived class. It also specifies that a class cannot be inherited from. It ensures that the function is virtual, otherwise a compile-time error is generated. Similarly when used in a class definition, it ensures that class cannot be used as base class by any other class.
Use of final in Class
In the below example Base
is a virtual class. Structure B is declared as final, so inheriting of this structure by structure C will give compilation error.
struct Base { virtual void foo(); }; struct B final : Base // struct B is final { void foo() final; }; struct C : B // Error: B is final { };
To resolve the error, either B should be declared as non final or C should not inherit structure B.
Use of final in Function
In the below example, structure A is overriding the function foo
using final keyword. So if structure B tries to override the function, compiler will give error.
struct Base { virtual void foo(); }; struct A : Base { void foo() final; // Base::foo is overridden and A::foo is the final override }; // struct B is final struct B final : A { void foo() override; // Error: foo cannot be overridden as it is final in A };
So final is also used to mark a virtual function so as to prevent it from being overridden in the derived classes.