`operator` — C++ Keyword

`operator` — C++ Keyword

The operator keyword in C++: defines overloaded operators for user-defined types.

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.

operator

Used to define overloaded operator functions for user-defined types, allowing objects to be used with standard C++ operators (+, ==, [], etc.).

Syntax

// Member operator
return-type operator symbol(params);

// Non-member (free) operator
return-type operator symbol(left-param, right-param);

// Conversion operator
explicit operator TargetType() const;

Example

#include <print>

struct Vec2 {
    double x, y;

    Vec2 operator+(const Vec2& o) const {
        return {x + o.x, y + o.y};
    }

    Vec2& operator+=(const Vec2& o) {
        x += o.x; y += o.y; return *this;
    }

    bool operator==(const Vec2& o) const = default;  // C++20 defaulted

    // Subscript
    double& operator[](int i) { return i == 0 ? x : y; }

    // Conversion to bool
    explicit operator bool() const { return x != 0 || y != 0; }
};

// Free-function shift-out for printing
std::ostream& operator<<(std::ostream& os, const Vec2& v) {
    return os << '(' << v.x << ',' << v.y << ')';
}

int main() {
    Vec2 a{1, 2}, b{3, 4};
    Vec2 c = a + b;
    std::println("{:.0f} {:.0f}", c.x, c.y);  // 4 6
    std::println("{}", (a == b));               // false
    std::println("{}", static_cast<bool>(a));   // true
}

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