In C++, we can prevent a class from being inherited by declaring it as final. When a class is declared as final, it cannot be used as a base class for any other class. This is useful when we want to prevent unintended modifications to a class’s behavior or implementation.
Here’s an example of how to declare a class as final:
class Base final {
// class implementation
};
In this example, the Base class is declared as final, which means it cannot be inherited by any other class. Any attempt to inherit from Base will result in a compilation error.
It’s important to note that marking a class as final does not prevent the creation of objects of that class. It only prevents inheritance from that class.
class Base final {
public:
void foo() {
cout << "Base::foo()" << endl;
}
};
class Derived : public Base { // compilation error: Base is final
public:
void bar() {
cout << "Derived::bar()" << endl;
}
};
int main() {
Base b;
b.foo(); // prints "Base::foo()"
// Derived d; // compilation error: Base is final
return 0;
}
In this example, the Base class has a single method foo(), which is accessible from objects of that class. We then try to define a Derived class that inherits from Base, but the attempt results in a compilation error because Base is declared as final.
By using the final keyword, we can ensure that our classes are used as intended and prevent unintended modifications to their behavior or implementation.