final
In C++, the final
keyword is used to prevent further inheritance or overriding. It can be applied in two main contexts:
- Preventing Class Inheritance: When applied to a class, final
indicates that the class cannot be derived from.
- Preventing Method Overriding: When applied to a virtual function in a base class, final
indicates that the function cannot be overridden by derived classes.
final
with ClassesWhen you mark a class as final, it cannot be used as a base class for any other class. This is useful when you want to design a class that should not be extended.
#include <iostream>
class Base final {
public:
void display() {
std::cout << "Base class display function" << std::endl;
}
};
// This will cause a compile-time error
// class Derived : public Base {
// };
int main() {
Base b;
b.display();
return 0;
}
The Base class is marked as final
, so any attempt to derive another class from Base
(like the commented Derived
class) will result in a compile-time error.
This ensures that Base
cannot be used as a base class for any other class.
final
with Virtual FunctionsWhen applied to a virtual function, final
prevents that function from being overridden in derived classes. This is useful when you want to lock down the implementation of a virtual function in a specific class.
#include <iostream>
class Base {
public:
virtual void show() final {
std::cout << "Base class show function" << std::endl;
}
};
class Derived : public Base {
public:
// This will cause a compile-time error
// void show() override {
// std::cout << "Derived class show function" << std::endl;
// }
};
int main() {
Derived d;
d.show(); // Calls Base::show()
return 0;
}
The show
function in the Base
class is marked as final
. This means it cannot be overridden by any class that derives from Base
.
Attempting to override show
in the Derived
class (as shown in the commented code) will result in a compile-time error.
In the main function, calling d.show()
will invoke the Base::show
method because the override attempt is disallowed.
final
on a Class: Prevents other classes from inheriting from this class.class MyClass final { ... };
virtual void myFunction() final { ... };
Using final
is a way to enforce design constraints, ensuring that certain classes or methods cannot be altered by subclassing or overriding, which can help maintain a stable and predictable class hierarchy.