| Lesson 3 | Overloadable Operators in C++ |
| Objective | Identify which C++ operators can and cannot be overloaded. |
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.
Almost all C++ operators can be overloaded to provide special meaning for your classes. They can be broadly categorized as follows:
+ (addition), - (subtraction), * (multiplication), / (division), % (modulo).==, !=, <, >, <=, >=, &&, ||, ! (logical NOT).& (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift).= (assignment), and all compound assignment operators like +=, -=, *=, etc.++ and -- operators. C++ provides a mechanism to define distinct behavior for both their prefix (e.g., ++obj) and postfix (e.g., obj++) forms.[]()->**->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.
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.
.): The fundamental dot operator for accessing members of an object cannot be changed..*): While its pointer-based counterpart ->* can be overloaded, the .* operator cannot.::): This operator is essential for navigating namespaces and class scopes and its meaning is fixed.?:): Its short-circuiting behavior and three-operand nature make it unsuitable for overloading.sizeof: This is an operator that works at compile-time to determine memory size and cannot have its behavior altered at runtime.It's important not to confuse operator overloading with function overloading.
operator followed by the symbol of the operator being overloaded (e.g., operator+, operator<<).