All Courses
OOP: OPERATOR OVERLOADING

Rules for Operator Overloading

C++ allows operator overloading, but it does not allow complete freedom. These rules protect the basic meaning and grammar of the language.

Rule 1: Only Existing Operators Can Be Overloaded

You cannot invent a new operator.

Invalid idea:

// operator** is not a C++ operator

If you need exponent behavior, use a named function:

power(a, b);

Rule 2: At Least One Operand Must Be User-Defined

You cannot change the meaning of operators for only built-in types.

Invalid idea:

// Cannot overload int + int

Valid idea:

Complex c3 = c1 + c2;

At least one operand must be a class, struct, enum, or another user-defined type.

Rule 3: Precedence Cannot Change

Operator precedence stays the same.

For example, * still has higher precedence than +.

a + b * c

The compiler still groups it like:

a + (b * c)

even if both operators are overloaded.

Rule 4: Associativity Cannot Change

Associativity also stays the same. For example, most binary arithmetic operators group left to right.

a + b + c

is still treated like:

(a + b) + c

Rule 5: Number of Operands Cannot Change

Unary operators still use one operand. Binary operators still use two operands.

You cannot make binary + work as a three-operand operator.

Rule 6: Some Operators Must Be Member Functions

These operators must be overloaded as member functions:

Operator Meaning
= assignment
[] subscript
() function call
-> member access through pointer-like object

They cannot be overloaded as ordinary global functions.

Rule 7: Return Type Should Match Natural Meaning

C++ may allow unusual return types, but good code follows expectation.

Good:

Money operator+(const Money& other) const;
bool operator==(const Money& other) const;

Confusing:

void operator+(const Money& other);

+ should usually return a new value. == should usually return bool.

Rule 8: Do Not Overload Without Natural Meaning

Only overload an operator when the meaning is obvious.

Good:

Distance total = d1 + d2;

Confusing:

Student result = s1 + s2;

Unless your program has a very clear meaning for adding students, this should be a named function.

Viva Answer

The main rules are: only existing operators can be overloaded, at least one operand must be user-defined, precedence and associativity cannot change, arity cannot change, and some operators like =, [], (), and -> must be member functions.

Quick Check

  1. Can we overload + for int + int?
  2. Can overloaded + be made higher precedence than *?
  3. Which four operators must be member functions?