The final specifier was introduced in C++11 to prevent further modification of class hierarchies. It can be used to stop a virtual function from being overridden or to prevent a class from being inherited.
- final can be applied to virtual functions and classes.
- It helps enforce design constraints and improves code safety.
Syntax of final
The final specifier can be used in the following ways:
virtual return_type function_name() final;
or
class ClassName final {
// class members
};
Using final with Virtual Functions
The final specifier can be applied to a virtual function to prevent derived classes from overriding it.
#include <iostream>
using namespace std;
class Base
{
public:
virtual void myfun() final
{
cout << "myfun() in Base";
}
};
class Derived : public Base
{
void myfun()
{
cout << "myfun() in Derived\n";
}
};
int main()
{
Derived d;
Base &b = d;
b.myfun();
return 0;
}
Output
prog.cpp:14:10: error: virtual function ‘virtual void Derived::myfun()’
void myfun()
^
prog.cpp:7:18: error: overriding final function ‘virtual void Base::myfun()’
virtual void myfun() final
Explanation
- myfun() is declared as a virtual function in the base class.
- The final specifier prevents any derived class from overriding it.
- The compiler generates an error when Derived attempts to redefine myfun().
Note: The final specifier can only be used with virtual functions.
Using final with Classes
The final specifier can also be used to prevent a class or structure from being inherited.
#include <iostream>
class Base final
{
};
class Derived : public Base
{
};
int main()
{
Derived d;
return 0;
}
Output
error: cannot derive from ‘final’ base ‘Base’ in derived type ‘Derived’
class Derived : public Base
Explanation
- The class Base is declared as final.
- Since Base cannot be inherited, the compiler reports an error when Derived attempts to inherit from it.
Advantages of Using final
The final specifier provides several benefits:
- Prevents derived classes from accidentally overriding important virtual functions.
- Restricts inheritance when extending a class is not desirable.
- Helps enforce object-oriented design constraints at compile time.
- Improves code readability, maintainability, and program safety.
Limitations of final
The final specifier also has some limitations:
- It can only be applied to virtual functions and classes.
- Classes marked as final cannot be used as base classes.
- Unlike Java, it cannot be used to create immutable variables or constants.