Operator Overloading
Normally + operator sirf numbers ke saath kaam karta hai. Operator overloading se apni custom classes (jaise Vector2D, Complex numbers) ke liye + ko redefine kar sakte ho, taaki obj1 + obj2 natural syntax mein likha ja sake, kisi function call (jaise add(obj1, obj2)) ke bajaye.
operator keyword se define karte hain: ReturnType operator+(const ClassName &other) { ... }. Compiler khud samajh leta hai ki jab bhi is class ke objects par + use hoga, ye function call hoga.
class Vector2D {
public:
double x, y;
Vector2D(double x, double y) : x(x), y(y) {}
Vector2D operator+(const Vector2D &other) {
return Vector2D(x + other.x, y + other.y);
}
};
int main() {
Vector2D v1(1, 2);
Vector2D v2(3, 4);
Vector2D v3 = v1 + v2; // operator+ call hota hai automatically!
cout << v3.x << ", " << v3.y << endl; // 4, 6
return 0;
}- operator+ (etc.) function se custom types ke liye operators redefine karo
- obj1 + obj2 natural syntax kaam karta hai
- Sirf intuitive cases mein overload karo — surprising behavior avoid karo
Comparison operators overload karna bahut common hai — custom types (jaise Point, Date) ko == se compare karna natural feel karata hai, member-by-member manual comparison likhne ke bajaye.
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
bool operator==(const Point &other) {
return x == other.x && y == other.y;
}
bool operator!=(const Point &other) {
return !(*this == other); // == ko reuse karo
}
};
int main() {
Point p1(1, 2), p2(1, 2);
cout << (p1 == p2) << endl; // 1 (true)
return 0;
}[] operator overload karna custom container-like classes (jaise apna khud ka array wrapper) ko normal array syntax dene deta hai — obj[i] likh sakte ho, obj.get(i) ki jagah.
class MyArray {
int data[10];
public:
int& operator[](int index) {
return data[index]; // reference return — assignment bhi possible
}
};
int main() {
MyArray arr;
arr[0] = 100; // operator[] set karta hai
cout << arr[0] << endl; // 100 — operator[] get bhi karta hai
return 0;
}