Operator overloading in C++ covers most operators, but a few are off-limits. The operators that cannot be overloaded are the scope resolution operator ::, the member access operator ., the pointer-to-member operator .*, and the conditional operator ?:. The sizeof and typeid operators can’t be overloaded either.
The operators that cannot be overloaded
- Scope resolution (
::) names something inside a namespace or class, as instd::cout. It refers to a name, not to a value that a function could take. - Member access (
.) selects a member of an object, as inv.x. The compiler resolves the member name directly, so there is no call to replace. - Pointer-to-member access (
.*) uses a pointer to a member to reach that member of an object, as inobj.*member_ptr. - Conditional (
?:) chooses one of two expressions, as inx > 0 ? x : -x. It evaluates only the branch it needs. A function call evaluates all of its arguments first, so a function couldn’t behave the same way. sizeofgives the size of a type or expression, as insizeof(int).typeidgives type information about a type or expression, as intypeid(x).
The compiler rejects an attempt to define one of them:
struct Widget {};
// Rejected: the conditional operator can't be overloaded.
Widget operator?:(bool, Widget, Widget);
Other limits on overloading
Some rules apply to every overloadable operator:
- At least one operand must be a class type or an enumeration. This line won’t compile:
int operator+(int a, int b); - You can’t create new operator symbols such as
**. - Precedence, associativity, and the number of operands don’t change.
=,[],(), and->must be non-static member functions.
What to do instead
If you need an operation that isn’t available as an operator, write a named function. For example, use power(base, exp) where you might have wanted **. For the operators you can overload and how to write them, see the overview of operator overloading in C++.
In short
Most operators can be overloaded, but ::, ., .*, ?:, sizeof, and typeid cannot. You also can’t invent new symbols, change precedence, or overload an operator for built-in types only.