Why can some operators only be overloaded as member functions, other as friend functions and the rest of them as both?

Viewed 12038

Why can some operators only be overloaded as member functions, other as non-member "free" functions and the rest of them as both?

What is the rationale behind those?

How to remember which operators can be overloaded as what (member, free, or both)?

4 Answers

The rationale is that it would not make sense for them to be non-members, as the thing on the left-hand side of the operator must be a class instance.

For example, assuming a class A

A a1;
..
a1 = 42;

The last statement is really a call like this:

a1.operator=(42);

It would not make sense for the thing on the LHS of the . not to be an instance of A, and so the function must be a member.

Because you can't modify the semantics of primitive types. It wouldn't make sense to define how operator= works on an int, how to deference a pointer, or how an array access works.

Related