In this blog post tutorial, you will learn about C++ final specifier with the help of programming examples. This blog post explains the use of the final keyword in C++ (final is context-sensitive). So let’s start this blog post with a question “What is the final specifier in C++”?
What is the final specifier in C++?
Specifier final came along with override in the C++11 standard. final specifier (since C++11) specifies that a virtual function cannot be overridden in a derived class or that a class cannot be derived from.
The final virt-specifier is used for two purposes. First, It prevents inheriting from classes, and second, it disables the overriding of a virtual function. It will be useful when you don’t want to allow the derived class to override the base class’ virtual function. We will understand it with programming examples.
Note:
The identifiers “final” have a special meaning when appearing in a certain context (eg, used after a function declaration or class name). Otherwise, it’s not a reserved keyword.
Final with virtual member function:
We already know that the final specifier prevents the overriding of a virtual function. So let’s see a programming example of how to use the final specifier with a virtual member function.
#include <iostream> using namespace std; //Base class class Base { public: /*Used final with virtual function*/ virtual void fun() final { cout << "Base class default Behaviour\n"; } }; //Derived class class Derived : public Base { public: /*compiler error: attempting to override a final function */ void fun() { cout << "Derived class overridden Behaviour\n"; } }; int main() { //object of derived class Derived obj; obj.fun(); return 0; }
Output:
error: overriding final function ‘virtual void Base::fun()
In the above example, we have used the final keyword with virtual function fun(). In the derived class we are trying to override the fun(), so getting a compiler error. Because the final specifier prevents overriding.
final with Classes:
Like the virtual member function, the final keyword can also apply to class and prevent it from inheriting. Let’s see an example where we use the final keyword to specify that the class cannot be inherited.
#include <iostream> using namespace std; //Base class class BaseClass final { }; /* compiler error: BaseClass is marked as non-inheritable */ class DerivedClass: public BaseClass { }; int main() { return 0; }
Output:
error: cannot derive from ‘final’ base ‘BaseClass’ in derived type ‘DerivedClass’
Recommended Articles for you:
- C++ Programming Courses And Tutorials.
- Polymorphism in C++ for example.
- MCQs on C++
- Compile Time Polymorphism with Templates in C++.
- Operator Overloading in C++ with some FAQ.
- Introduction of reference in C++.
- Use of mutable keywords in C++.
- Best electronic kits for programmers.
- References and const in C++ with example programs.
- C++ Interview Questions with Answers.
- List of some Best C++ Books, you must see.