Operator Overloading

Which Operators Cannot Be Overloaded in C++?

The scope resolution, member access, pointer-to-member, and conditional operators can't be overloaded in C++. Here is the full list and the rules behind it.

On this page
  1. The operators that cannot be overloaded
  2. Other limits on overloading
  3. What to do instead
  4. In short

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 in std::cout. It refers to a name, not to a value that a function could take.
  • Member access (.) selects a member of an object, as in v.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 in obj.*member_ptr.
  • Conditional (?:) chooses one of two expressions, as in x > 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.
  • sizeof gives the size of a type or expression, as in sizeof(int).
  • typeid gives type information about a type or expression, as in typeid(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.

The complete guide to operator overloading

Operator Overloading in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Is C++ Harder Than Python?

For most beginners, C++ is harder than Python because it needs a compiler, explicit types and careful memory handling. See why, with a side-by-side example.

C++ vs Python 4 min read