Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

final — preventing overriding and inheritance

The final specifier prevents further overriding of a virtual function or use of a class as a base class. These restrictions are checked at compile time. It does not make an object immutable and does not replace override.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

struct Sealed final : Base { /* members */ };
struct Derived : Base {
    int value() const override final;
};

final has two uses. In a class definition, place it after the name and before any :, for example struct Leaf final : Fixed {};. That class cannot be a base class, even if it has no virtual functions. This restriction applies to both class and struct.

In a virtual function declaration, final follows the declarator, including qualifiers such as const, for example int value() const override final;. It prevents that function from being overridden in further derived classes, but does not prevent inheritance from the class itself. The function must be virtual: it can declare virtual or override an inherited virtual function.

override checks that a function overrides a base-class function; final prevents subsequent overrides. Both can be used, in either order: override final or final override. Violating either the overriding or inheritance restriction is a compile-time error. final does not make an object const.

In the example, Fixed::value is still called through a Base reference, and Leaf can inherit from Fixed but cannot have derived classes itself. Technically, final is an identifier with special meaning in particular contexts, rather than a universally reserved keyword. The supplied source is an evolving working draft, not a frozen C++23 text; the example is intended for verification in C++23 mode.

Examples

#include <iostream>

struct Base {
    virtual int value() const { return 1; }
    virtual ~Base() = default;
};

struct Fixed : Base {
    int value() const override final { return 7; }
};

struct Leaf final : Fixed {};

// struct BadOverride : Fixed {
//     int value() const override { return 9; }
// };
// struct BadInheritance : Leaf {};

int main() {
    Leaf object;
    const Base& base = object;
    std::cout << base.value() << '\n';
}

Result

7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources