C++ Operator Overloading
Operator Overloading
You already know that the + operator does different things for different types. It can be used to add two numbers, and to join two strings.
But for your own classes, C++ does not know what + should do. With operator overloading, you decide what an operator does for objects of your class.
To overload an operator, create a method called operator followed by +, like operator+:
Example
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;
}
p1 + p2 calls p1.operator+(p2). The method adds the x values and the y values, and returns a new Point.
Compare Objects with ==
In the same way, you can overload == to decide when two objects are equal. The method returns a bool:
Example
class Point {
public:
int x, y;
Point(int x, int y) {
this->x = x;
this->y = y;
}
bool operator==(Point other) {
return x == other.x && y == other.y;
}
};
Point p1(1, 2);
Point p2(1, 2);
if (p1 == p2) {
cout << "The points are equal";
} else {
cout << "The points are not equal";
}
Print Objects with <<
You can also make cout print your objects, by overloading the << operator. This is done with a function outside the class, because the left side of << is cout, not your object:
Example
Using the Point class from the first example:
ostream& operator<<(ostream& out, Point p) {
out << "(" << p.x << ", " << p.y << ")";
return out;
}
Point p1(1, 2);
Point p2(3, 4);
cout << p1 + p2;
The function gets the output stream (out) and the point, writes the point to the stream, and returns the stream. Returning it lets you keep using << after the point, like cout << p << "\n";.
Tip: Only overload operators when the meaning is obvious, like + for adding two points. If it is not clear what an operator does, use a normal method with a good name instead.