CodeBlanks Logo Icon CodeBlanks

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.

Practice 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().

Starter code

main.cpp
#include <iostream>

// Define Animal and Dog classes here

int main() {
    // Create a Dog instance and call speak
    return 0;
}

Sample solution

main.cpp
#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;
}

Expected output

Woof

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each use to its role

Term Meaning
class Dog final Class inheritance closed
void speak() final Function override closed
override final Override and lock
class Dog : public Animal Inheritance open

2 After class Dog final : public Animal { };, what happens?

main.cpp
class Dog final : public Animal { };
  • Dog can no longer inherit from Animal
  • Dog's members are deleted
  • No class can derive from Dog Correct answer
  • Dog's constructor is hidden

Explanation: final prevents any class from deriving from Dog.

3 Write the final keyword

Question
class Dog ____ : public Animal { };
Answer
class Dog final : public Animal { };

Explanation: final prevents inheriting from Dog.

All lessons in Intermediate