Operator Overloading
C++ aapko define karne deta hai ki + jaisa ek operator apne khud ke type ke liye kya matlab rakhta hai, ek method implement karke jiska naam operator+ hai. Yeh is site ke har doosre course ke comparison mein genuinely distinctive hai: Python ke paas isi tarah ke purpose ke liye dunder methods hain, lekin yahan koi bhi doosri language ek type ko bilkul wahi operator syntax use karne nahi deti jo built-in numeric types use karte hain.
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
Point operator+(const Point& other) const {
return Point(x + other.x, y + other.y);
}
};
int main() {
Point a(1, 2);
Point b(3, 4);
Point c = a + b;
cout << "(" << c.x << ", " << c.y << ")" << endl;
return 0;
}(4, 6)
a + b, peeche se a.operator+(b) call karta hai — syntax bilkul do numbers add karne jaisa padhta hai, halaanki Point ek type hai jo aapne define kiya hai. Constructor mein : x(x), y(y) syntax ek member initializer list hai, ek C++ class ke fields ko uske constructor parameters se directly set karne ka idiomatic tarika.
Aage: templates — C++ ka apna compile-time mechanism, ek function ya class likhne ke liye jo kai types ke across kaam kare.
Practice exercise
Ek class Vec2 define karo jiske int x, y aur ek constructor ho. operator+ ko overload karo taaki do Vec2s add karne par unke components add hon. Vec2(2, 3) aur Vec2(4, 1) add karo, phir result ka x aur y ek space se separate karke print karo.