You can add two ints with +. Wouldn't it be nice to add two of your own objects the same way? With operator overloading you can tell C++ what +, ==, << and friends mean for your class.
#include <iostream>
using namespace std;
struct Money {
int dollars;
int cents;
Money operator+(const Money& other) const {
int total = (dollars + other.dollars) * 100 + cents + other.cents;
return {total / 100, total % 100};
}
bool operator==(const Money& other) const {
return dollars == other.dollars && cents == other.cents;
}
};
int main() {
Money a = {5, 70};
Money b = {2, 50};
Money c = a + b; // calls a.operator+(b)
cout << c.dollars << " dollars " << c.cents << " cents\n";
cout << boolalpha << (c == Money{8, 20}) << "\n";
return 0;
}Output
8 dollars 20 cents true
An operator is just a function with a special name: operator+, operator==, and so on. a + b is simply a nicer way of writing a.operator+(b).
Printing your objects with <<
To make cout << myObject work, write an operator<< function outside the class. It takes the stream and your object, and returns the stream so you can keep chaining:
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
ostream& operator<<(ostream& out, const Point& p) {
out << "(" << p.x << ", " << p.y << ")";
return out;
}
int main() {
Point a = {3, 4};
Point b = {-1, 7};
cout << "a is " << a << " and b is " << b << "\n";
return 0;
}Output
a is (3, 4) and b is (-1, 7)
operator< makes sorting easy
If your type has operator<, sort knows how to put objects in order:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Player {
string name;
int score;
bool operator<(const Player& other) const {
return score < other.score;
}
};
int main() {
vector<Player> players = {{"Ann", 30}, {"Bob", 10}, {"Cid", 20}};
sort(players.begin(), players.end());
for (const Player& p : players) {
cout << p.name << " " << p.score << "\n";
}
return 0;
}Output
Bob 10 Cid 20 Ann 30
Tip: Only overload operators when the meaning is obvious.
+to add money: great.+to delete a file: confusing!