Operator Overloading
For two int values, + adds them. For two strings, + joins them. C++ already knows what + means for these types. For a type you made yourself, it does not, so the compiler stops:
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
int main() {
Point a = {1, 2};
Point b = {3, 4};
Point c = a + b;
cout << c.x << "\n";
return 0;
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:12:17: error: no match for ‘operator+’ (operand types are ‘Point’ and ‘Point’)
operator+ is the name C++ uses for the + sign. The error says that there is no + that takes two Point values. You can write one yourself. This is called operator overloading: giving an operator a meaning for your own type.
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
Point operator+(Point a, Point b) {
return {a.x + b.x, a.y + b.y};
}
int main() {
Point a = {1, 2};
Point b = {3, 4};
Point c = a + b;
cout << c.x << " " << c.y << "\n";
return 0;
}
Output:
4 6
An operator is a function with a special name: the word operator and then the sign. Its two parameters are the values on the left and the right of the +. So a + b calls operator+(a, b).
return {a.x + b.x, a.y + b.y}; builds the new Point from the values in the braces, in member order, just like Point a = {1, 2};. The return type is Point, so C++ knows what to build.
Comparing with ==
== works the same way, but it returns a bool:
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
bool operator==(Point a, Point b) {
return a.x == b.x && a.y == b.y;
}
int main() {
Point a = {1, 2};
Point b = {1, 2};
Point c = {2, 1};
cout << (a == b) << "\n";
cout << (a == c) << "\n";
return 0;
}
Output:
1
0
cout prints a bool as 1 or 0, so 1 means true. Two points are equal only when both parts match. c has the same numbers as a, but in a different order, so a == c is false.
Printing with <<
In the Enums lesson, cout << now failed with no match for ‘operator<<’. Now you can write that operator. Here it is for Point:
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
ostream& operator<<(ostream& out, Point p) {
out << "(" << p.x << ", " << p.y << ")";
return out;
}
int main() {
Point a = {1, 2};
Point b = {3, 4};
cout << a << " and " << b << "\n";
return 0;
}
Output:
(1, 2) and (3, 4)
This one has more parts:
ostreamis the type ofcout. The left side of<<iscout, so the first parameter is anostream.- It is a reference (
ostream&), because the function must write into the realcout, not into a copy. - The function writes into
outthe same way you write intocout. - It returns
out, so the next<<in the line can keep going. That is howcout << a << " and " << bworks.
Only overload an operator when its meaning is clear. Adding two points is clear. Using + for something that is not like adding makes code harder to read.
In the exercise, write + and == for a Point struct. The << operator is already written for you.