Operator overloading means giving a new meaning to an operator (like +, -, *, []) when it is used with objects.
- With operator overloading, we can make operators work for user defined classes structures.
- It is an example of compile-time polymorphism.
Example: In this example, the + operator is overloaded to add two Number objects.
Why use Operator Overloading?
- Allows objects to behave like basic data types.
- Useful for mathematical objects like Complex numbers and Vectors.
- Reduces the need for extra function calls.
Operator Functions vs Normal Functions
Feature | Operator Function | Normal Function |
|---|
Syntax | Uses operator keyword | Standard function name |
|---|
Invocation | Triggered by using an operator | Called explicitly by name |
|---|
Purpose | Redefines behavior of operators | Performs defined actions |
|---|
Example | operator+() | add() |
|---|
Operators That Cannot Be Overloaded
The following operators cannot be overloaded in C++:
- sizeof
- typeid
- Scope resolution (::)
- Class member access operators (. and .*)
- Ternary / conditional operator (?:)
Why These Operators Cannot Be Overloaded?
1. sizeof Operator
- Evaluated at compile time
- Used internally for memory layout and pointer arithmetic
- Overloading would break fundamental language behavior
2. typeid Operator
- Used for runtime type identification
- Must uniquely identify a type
- Altering its meaning would break RTTI and polymorphism guarantees
3. Scope resolution (::) Operator
- Works on names, not values
- Fully resolved at compile time
- There is no syntax to intercept or overload name resolution
4. Class Member Access Operators (. and .*)
- Implicitly used by the compiler to access members
- Overloading would break object access semantics
The importance and implicit use of class member access operators can be understood through the following example:
Explanation:
- "c1 + c2" is translated internally to "c1.operator+(c2)"
- The dot operator is implicitly required to invoke member functions
- Since this operator is fundamental to object access, it cannot be overloaded
5. Ternary or conditional (?:) Operator
- Evaluates only one of the two expressions based on a condition
- Function calls cannot enforce short-circuit evaluation
- Overloading would break conditional execution guarantees
Important Points About Operator Overloading
- At least one operand must be a user-defined type
- Operators can be overloaded as member or non-member functions
- Some operators (like conversion operators) must be member functions
Conversion Operator Example:
Note: Conversion operators must be member functions.
Conversion Constructors
Any constructor that can be called with a single argument acts as a conversion constructor and enables implicit type conversion.