`final` — C++ Keyword

`final` — C++ Keyword

The final keyword in C++: prevents further overriding of a virtual function or further inheritance from a class.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

final

A context-sensitive keyword that either (1) prevents further inheritance from a class, or (2) prevents a virtual function from being overridden in more-derived classes.

Syntax

class Name final { ... };                        // cannot be inherited
virtual return-type func(params) final;          // cannot be overridden further

Example

#include <print>

class Base {
public:
    virtual void greet() const { std::println("Base"); }
    virtual ~Base() = default;
};

class Derived : public Base {
public:
    void greet() const override final {
        std::println("Derived – cannot be overridden further");
    }
};

// class MoreDerived : public Derived {
//     void greet() const override {}  // error: greet is final
// };

class Leaf final : public Derived {};

// class Child : public Leaf {};   // error: Leaf is final

int main() {
    Leaf l;
    l.greet();   // Derived – cannot be overridden further
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}