C++
final
Learn to prevent inheritance with final.
final
Since C++11, the final keyword prevents a class from being inherited further or a function from being overridden further. It is used to close a class hierarchy or protect critical functions from changing.
For a class: class Dog final : public Animal { };. You can no longer write Puppy : public Dog; you get a compile error. For a function: void speak() override final { }. This means a class deriving from Dog cannot override speak again. final documents a design decision explicitly.
Why use final?
final is used for two main reasons. First, performance: if all virtual functions in a base class are final, the compiler can sometimes turn virtual calls into direct calls. Second, design: you may want to intentionally prevent a class from being extended.
Example: if a password-checking class is closed as class Authenticator final { ... };, no one can write a derived class that introduces a security hole. Similarly, if a function is final, subclasses cannot change it to produce unexpected behavior. This helps library designers preserve their contract.
Exercise Make the Dog class final
Define an Animal class: under public: virtual void speak() { std::cout << "Sound"; }. Derive Dog from Animal as final: class Dog final : public Animal { public: void speak() override { std::cout << "Woof"; } };. In main create Dog dog; and call dog.speak().
Show example solution
#include <iostream>
class Animal {
public:
virtual void speak() {
std::cout << "Sound";
}
};
class Dog final : public Animal {
public:
void speak() override {
std::cout << "Woof";
}
};
int main() {
Dog dog;
dog.speak();
return 0;
}
Test yourself
-
Match each use to its role
- class Dog final
- Class inheritance closed
- void speak() final
- Function override closed
- override final
- Override and lock
- class Dog : public Animal
- Inheritance open
-
After class Dog final : public Animal { };, what happens?
class Dog final : public Animal { };
- Dog can no longer inherit from Animal
- Dog's members are deleted
- No class can derive from Dog
- Dog's constructor is hidden
Show answer
No class can derive from Dog — final prevents any class from deriving from Dog.
-
Write the final keyword
class Dog ____ : public Animal { };
Show answer
class Dog final : public Animal { };
Next lesson: Summary - Inheritance