C++ operator Keyword
Example
Overload the + operator to add two Point objects:
class Point {
public:
int x, y;
Point(int x, int y) {
this->x = x;
this->y = y;
}
Point operator+(Point other) {
return Point(x + other.x, y + other.y);
}
};
int main() {
Point p1(1, 2);
Point p2(3, 4);
Point p3 = p1 + p2;
cout << p3.x << ", " << p3.y;
return 0;
}
Definition and Usage
The operator keyword is used to overload an operator. This means that you decide what an operator, like + or ==, does for objects of your own class.
Write operator followed by the symbol, like operator+, and use it as the name of a method. In the example above, p1 + p2 calls p1.operator+(p2), which adds the x values and the y values, and returns a new Point.
Related Pages
Read more about operator overloading in our C++ Operator Overloading Tutorial.