Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Operator function declaration

An operator function declaration gives a function a name consisting of operator followed by an overloadable operator designation, such as operator+. It defines how an operator works for user-defined types without changing its precedence or associativity.

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

Syntax

ReturnType operator+(const T& lhs, const T& rhs);
// Alternative member declaration inside T:
ReturnType operator+(const T& rhs) const;

Operator function declaration uses a name such as operator+. It declares a function or function template; explicit instantiations and specializations of a template are also possible. The first operator+ declaration in the example has no function body. A trailing ; alone does not tell you whether a declaration is a definition: = delete; is a function body in the C++ grammar, so a declaration with that body is a definition.

For an ordinary binary operator such as +, a non-member function has two parameters. Alternatively, a non-static member function has one non-object parameter: the left operand is the object. Overload resolution selects the function for a + b. In the example, the selected non-member function is also called explicitly as operator+(a, b).

An ordinary overload requires a class or enumeration type to participate, so it cannot redefine addition of two int values. It does not change precedence, associativity, or operand count. The operators ., .*, ::, and ?: cannot be overloaded. Allocation and deallocation functions and co_await follow separate rules.

The example first declares operator+, then defines it. Both calls add the value fields and create a new Score without modifying the arguments. Expected output is 20 20 followed by a newline. This entry targets C++23; the supplied document is an evolving standard draft, not a frozen C++23 edition.

Examples

#include <iostream>

struct Score {
    int value;
};

Score operator+(const Score& lhs, const Score& rhs);

Score operator+(const Score& lhs, const Score& rhs) {
    return Score{lhs.value + rhs.value};
}

int main() {
    const Score a{12};
    const Score b{8};
    const Score sum = a + b;
    const Score direct = operator+(a, b);
    std::cout << sum.value << ' ' << direct.value << '\n';
}

Result

20 20

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