Definition
Operator overloading allows you to redefine or “overload” the behavior of C++ operators (+, -, , ++, etc.) for **user-defined data types (classes/objects).*
Syntax:
return_type operator operator_symbol (parameters) {
// operation definition
}
For example:
Complex operator + (Complex obj);
Why Use Operator Overloading?
- Improves code readability – You can write expressions like obj1 + obj2 instead of calling a function.
- Extends usability of operators to user-defined types (like classes).
- Makes code intuitive – Works naturally with custom data types such as Complex, Matrix, Vector, etc.
- Encapsulation – Keeps the logic of object operations within the class.
Unary Operator Overloading (Example: ++ operator)
#include <iostream>
using namespace std;
class Number {
int x;
public:
Number(int a = 0) {
x = a;
}
// Unary operator overloading for ++
void operator ++() {
x = x + 1; // x ko increase kar diya
}
void display() {
cout << "Value of x: " << x << endl;
}
};
int main() {
Number n1(5);
cout << "Before increment: ";
n1.display();
++n1; // yahan operator overloading call hui
cout << "After increment: ";
n1.display();
return 0;
}
Output
Before increment: Value of x: 5
After increment: Value of x: 6
Example Without Constructor (Unary Operator Overloading)
#include <iostream>
using namespace std;
class Number {
public:
int x; // public rakha taki direct assign kar sake
// Unary operator overloading
void operator ++() {
x = x + 1;
}
void show() {
cout << "Value of x: " << x << endl;
}
};
int main() {
Number n1;
n1.x = 10; // value manually set ki, constructor nahi use hua
++n1; // operator overloading call hua
n1.show();
return 0;
}
Binary Operator Overloading (Example: + operator)
#include <iostream>
using namespace std;
class Add {
int a;
public:
Add(int x = 0) {
a = x;
}
// Binary operator overloading for +
Add operator + (Add obj) {
Add temp;
temp.a = a + obj.a; // dono object ki value add
return temp;
}
void display() {
cout << "Sum: " << a << endl;
}
};
int main() {
Add obj1(5), obj2(10), obj3;
obj3 = obj1 + obj2; // operator overloading call hui
obj3.display();
return 0;
}
Output
Sum: 15
Example Without Constructor (Binary Operator Overloading)
#include <iostream>
using namespace std;
class Add {
public:
int a;
Add operator + (Add obj) {
Add temp;
temp.a = a + obj.a;
return temp;
}
void show() {
cout << "Sum: " << a << endl;
}
};
int main() {
Add obj1, obj2, obj3;
obj1.a = 5;
obj2.a = 15;
obj3 = obj1 + obj2; // operator overloading call hua
obj3.show();
return 0;
}
Top comments (0)