C++ final Keyword
Example
A final class cannot be inherited:
class Vehicle {
public:
string brand = "Ford";
};
class Car final : public Vehicle {
public:
string model = "Mustang";
};
// class SportsCar : public Car {}; // Error, because Car is final
int main() {
Car myCar;
cout << myCar.brand + " " + myCar.model;
return 0;
}
Definition and Usage
The final keyword prevents a class from being inherited. Write it after the class name, like class Car final.
You can also write final after a virtual method. Then child classes cannot override the method (write their own version of it).
final (like override) is not a reserved word, so you can still use it as a name. It only has a special meaning in a class.
Related Pages
Read more about inheritance in our C++ Inheritance Tutorial, and about virtual methods in our C++ Virtual Functions Tutorial.