Operator Overloading  «Prev  Next»
Lesson 3 Overloadable Operators in C++
Objective Identify which C++ operators can and cannot be overloaded.

A Guide to Overloadable Operators in C++

In C++, operator overloading allows you to redefine the behavior of most built-in operators for user-defined types (like classes or structs). This can make code more intuitive and readable by allowing objects to be manipulated with familiar syntax. However, not all operators can be overloaded. This guide outlines which operators you can customize and which you cannot.


Overloadable Operators

Almost all C++ operators can be overloaded to provide special meaning for your classes. They can be broadly categorized as follows:

  1. Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulo).
  2. Comparison and Logical Operators: ==, !=, <, >, <=, >=, &&, ||, ! (logical NOT).
  3. Bitwise Operators: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift).
  4. Assignment Operators: = (assignment), and all compound assignment operators like +=, -=, *=, etc.
  5. Increment and Decrement: The ++ and -- operators. C++ provides a mechanism to define distinct behavior for both their prefix (e.g., ++obj) and postfix (e.g., obj++) forms.
  6. Member Access and Subscripting:
    • The subscript operator: []
    • The function call operator: ()
    • The pointer-to-member access operator: ->*
    • The indirection (dereference) operator: *
    • The structure dereference operator: ->
  7. Memory Management: The new, new[], delete, and delete[] operators can be overloaded to customize memory allocation and deallocation for a class.

Note: The assignment =, function call (), subscript [], and class member access -> operators can only be overloaded as non-static member functions.


Non-Overloadable Operators

For reasons of language consistency and safety, C++ explicitly forbids the overloading of a few core operators. Attempting to overload them will result in a compile-time error.

  1. Member Access (.): The fundamental dot operator for accessing members of an object cannot be changed.
  2. Pointer-to-Member Access (.*): While its pointer-based counterpart ->* can be overloaded, the .* operator cannot.
  3. Scope Resolution (::): This operator is essential for navigating namespaces and class scopes and its meaning is fixed.
  4. Ternary Conditional (?:): Its short-circuiting behavior and three-operand nature make it unsuitable for overloading.
  5. sizeof: This is an operator that works at compile-time to determine memory size and cannot have its behavior altered at runtime.

Operator Overloading vs. Function Overloading

It's important not to confuse operator overloading with function overloading.


Operator Overloading - Quiz

Click the Quiz link below to take a brief multiple-choice quiz on which operator can be overloaded.
Operator Overloading - Quiz

SEMrush Software