OBJECT ORIENTED
PROGRAMMING
Chapter 7: Operator Overloading in C++
Er. Sudeeip Bhandarri
Operator Overloading
Operator Overloading allows us to define how operators (+, -, *, etc.) behave
with user-defined data types (classes).
Restrictions:
● Cannot overload: ::, .*, ., ?:, sizeof
● Cannot create new operators
● At least one operand must be a user-defined type
Why Use Operator Overloading?
Operator overloading allows you to:
1. Make user-defined data types behave like built-in types
○ For example, you can use + to add two Complex numbers, just like you add integers.
2. Write cleaner, readable, and more intuitive code
○ Instead of calling functions like add(obj1, obj2), you can simply write obj1 + obj2.
3. Increase code reusability and flexibility
○ You can define how operators should work for different objects in different situations.
When to Use Operator Overloading??
Rules for Operator Overloading
● Can’t overload all operators
● At least one operand must be user-defined
● Preserves precedence and associativity
● Usually declared as member or friend function
s1.operator+(s2);
internally calling
Overloading
Unary Operator
Overloading + Operator
using Friend Function
Object to
basic type
Basic Type (int)
to Object
Conversion