12.1 — Operator overloading
Read one box at a time. No rush.
Teach + and << about your types#
3 + 4 works because C++ knows how to add ints. But what about your own types?
C++
struct Money{ int dollars {}; int cents {};}; Money a { 2, 50 };Money b { 1, 75 };Money c { a + b }; // error: C++ doesn't know how to add MoneyOperator overloading lets you teach it. You write a function named operator+.
Writing operator+#
C++
Money operator+(const Money& a, const Money& b){ int totalCents { (a.dollars + b.dollars) * 100 + a.cents + b.cents }; return Money { totalCents / 100, totalCents % 100 };}Now a + b works, and gives Money { 4, 25 }.
Printing with <<#
To print with std::cout, overload operator<<:
C++
std::ostream& operator<<(std::ostream& out, const Money& m){ out << '$' << m.dollars << '.' << (m.cents < 10 ? "0" : "") << m.cents; return out;}C++
std::cout << a + b << '\n';Output
$4.25Key idea
operator<< takes the stream by reference and returns it. That is what lets you chain: std::cout << a << b.
Comparing: ==#
C++
bool operator==(const Money& a, const Money& b){ return a.dollars == b.dollars && a.cents == b.cents;}The spaceship operator (C++20)
Adding auto operator<=>(const Money&) const = default; inside the struct gives you ==, !=, <, >, <= and >= all at once.
Good habit
Only overload an operator when its meaning is obvious. + on Money is clear. + on a Player would be confusing — use a named function instead.
Tip: press ← / → to move between lessons, / to search.