final keyword
It is used to prevent the virtual function (cannot apply to normal function) from being overridden in derived class. It is also used to prevent the class being used as “Base class”.
It can be placed after virtual function or class name only.
I have not used it in my career but it has been asked many times in interviews.
source code with example:
#include<iostream> #include<memory> class Base final { public: void fun01(){std::cout<<"In Base fun01"<<std::endl;} virtual void fun02 () final {std::cout<<"In Base fun02"<<std::endl;} }; class Derived:public Base { public: virtual void fun02(){std::cout<<"In Derived fun01"<<std::endl;} }; int main() { std::cout<<"In Final"<<std::endl; std::unique_ptr<Base> upB = std::make_unique<Derived>(); upB->fun02(); return 0; }
Output:
g++ final.cpp final.cpp:11:7: error: cannot derive from ‘final’ base ‘Base’ in derived type ‘Derived’ class Derived:public Base final.cpp:14:15: error: virtual function ‘virtual void Derived::fun02()’ virtual void fun02(){std::cout<<"In Derived fun01"<<std::endl;} final.cpp:8:15: error: overriding final function ‘virtual void Base::fun02()’ virtual void fun02 () final