`override` — C++ Keyword

`override` — C++ Keyword

The override keyword in C++: marks a virtual function as intentionally overriding a base class virtual.

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.

override

A context-sensitive keyword that explicitly marks a virtual member function as overriding a base-class virtual. The compiler verifies the override is valid and issues an error if no matching virtual exists.

Syntax

struct Derived : Base {
    return-type function-name(params) override;
};

Example

#include <print>

struct Animal {
    virtual std::string sound() const { return "..."; }
    virtual ~Animal() = default;
};

struct Dog : Animal {
    std::string sound() const override { return "Woof"; }
};

struct Cat : Animal {
    std::string sound() const override { return "Meow"; }
};

// Uncommenting the line below would be a compile error:
// std::string soudn() const override { return "?"; }  // typo – no base virtual

int main() {
    Dog d;
    Cat c;
    std::println("{}", d.sound());  // Woof
    std::println("{}", c.sound());  // Meow
}

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;
}