Final Specifier in C++
Hello Learners, today we are going to learn a very interesting topic that is: How to use the keyword final in C++ and its functions. The main function of using the final keyword is – it can reduce the overriding of the function. And it is also used in the inheritance.
We will try to understand the final keyword with an example:
final int i=10; i=3; cout<<i;
if you see the above code carefully, the output will be 10, not 3. Once if you have declared the variable with the final keyword, the value of the variable remains the same.
C++: Program for the final specifier
Now we will start performing the code for the function overriding and inheritance using the final keyword, and we will understand how it works.
Final keyword used in base class in inheritance in C++
#include<iostream> using namespace std; class base_class final { public: void function() { cout<<"this is base class code space"; } }; class derived_class :public base_class { void function() { cout<<"this is derived class code space"; } }; int main() { derived_class d; base_class &b=d; b.function(); return 0; }
You will get an error like this:
error: cannot derive from ‘final’ base ‘base_class’ in derived type ‘derived_class’ class derived_class :public base_class
Because we have declared the base class as final, so due to this reason we cannot derive the properties of base class to the derived class. So, By this code we can understand that if we don’t inherit the properties of base class to derived class then we can do with the help of the final keyword.
Final keyword used in function overriding in C++
#include<iostream> using namespace std; class base_class { public: virtual void function() final { cout<<"this is base class code space"; } }; class derived_class :public base_class { void function() { cout<<"this is derived class code space"; } }; int main() { derived_class d; base_class &b=d; b.function(); return 0; }
In the above code you will get an error:
error: overriding final function ‘virtual void base_class::function()’ virtual void function() final
This is because once if a function is declared with a final keyword, the same function can’t be used again and again as we use it in function overriding. So to decrease the function overriding concept we use the keyword final.
This is all about the final specifier in C++. If you have any doubts, please ask in the comment section given below.
Leave a Reply