๐ What is Operator Overloading?
In C++, operator overloading allows you to define or change the behavior of operators (like +
, -
, ++
, ==
) for user-defined types (classes).
Operators can be overloaded as:
- Unary operators: Operate on a single operand (e.g.,
++
,--
,-
) - Binary operators: Operate on two operands (e.g.,
+
,-
,*
,/
)
๐น Overloading Unary Operators
โ Definition:
Unary operators take one operand and can be prefix or postfix.
โ๏ธ Syntax (as member function):
return_type operator op();
๐งช Example: Overloading Unary -
Operator
#include <iostream>
using namespace std;
class Number {
private:
int value;
public:
Number(int v) : value(v) {}
void operator - () { // Overloading unary minus
value = -value;
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Number n(5);
-n; // Unary minus
n.display(); // Output: -5
return 0;
}
๐ธ Overloading Binary Operators
โ Definition:
Binary operators work with two operands (like +
, -
, *
, ==
).
โ๏ธ Syntax (as member function):
return_type operator op (const ClassName &obj);
๐งช Example: Overloading +
Operator
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int a = 0, int b = 0) : x(a), y(b) {}
// Overload + operator
Point operator + (const Point &p) {
return Point(x + p.x, y + p.y);
}
void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1(2, 3), p2(4, 5);
Point p3 = p1 + p2; // Calls overloaded +
p3.display(); // Output: (6, 8)
return 0;
}
๐ Rules for Operator Overloading in C++
- Only existing operators can be overloaded (not new ones).
- Some operators cannot be overloaded:
::
(scope resolution).
(member access).*
(pointer-to-member)sizeof
,typeid
,?:
,const_cast
, etc.
- Operator overloading must preserve the number of operands.
- Unary โ one operand
- Binary โ two operands
- At least one operand must be a user-defined type (class object).
- Cannot change precedence or associativity of an operator.
- Overloaded operators can be:
- Member functions (usually preferred)
- Friend functions (when the left operand is not a class object)
๐ Summary Table
Operator Type | Example | Overloaded Function |
---|---|---|
Unary | -n | operator-() |
Binary | a + b | operator+(const Obj &b) |
โ Benefits of Overloading
- Makes class objects behave like primitive types
- Improves readability and natural syntax
- Allows intuitive expressions using user-defined data types