Object-Oriented Programming · Lesson 12 of 33
Operator Overloading in C++
Operator overloading lets your own types use natural syntax: add two Money values with +, compare Versions with <, print a Point with <<. It's how std::string supports + and ==. Used well, it makes code read like the problem; used badly, it confuses everyone – so this lesson covers the rules too.
In this lesson
- Arithmetic operators as members and free functions
- Comparisons with the C++20 spaceship operator
<=> - Printing with
operator<< - Subscript and the rules of good overloading
Arithmetic operators
#include <iostream>
class Money { // stores paise to avoid floating-point errors
public:
explicit Money(long long paise = 0) : paise_(paise) {}
static Money rupees(long long r, int p = 0) { return Money(r * 100 + p); }
Money& operator+=(const Money& other) { paise_ += other.paise_; return *this; }
Money operator-() const { return Money(-paise_); } // unary minus
long long paise() const { return paise_; }
private:
long long paise_;
};
Money operator+(Money a, const Money& b) { return a += b; } // free function, built on +=
Money operator*(const Money& m, int qty) { return Money(m.paise() * qty); }
std::ostream& operator<<(std::ostream& os, const Money& m) {
long long p = m.paise() < 0 ? -m.paise() : m.paise();
return os << (m.paise() < 0 ? "-" : "") << "Rs " << p / 100 << '.' << (p % 100 < 10 ? "0" : "") << p % 100;
}
int main() {
Money pen = Money::rupees(20, 50), book = Money::rupees(450);
Money total = pen * 3 + book;
std::cout << "total " << total << '\n';
total += Money::rupees(9, 99);
std::cout << "with delivery " << total << ", refund " << -pen << '\n';
return 0;
}
total Rs 511.50 with delivery Rs 521.49, refund -Rs 20.50
The canonical pattern
Implement the compound operator (+=) as a member that returns *this by reference, then write + as a free function using it. Free functions treat both operands equally, so mixed expressions like 3 * money can also be supported.
Comparisons with <=> (C++20)
#include <algorithm>
#include <compare>
#include <iostream>
#include <vector>
struct Version {
int major = 0, minor = 0, patch = 0;
auto operator<=>(const Version&) const = default; // generates <, <=, >, >= (and == with it)
};
int main() {
Version a{1, 4, 2}, b{1, 10, 0}, c{1, 4, 2};
std::cout << std::boolalpha << (a < b) << ' ' << (a == c) << ' ' << (b >= a) << '\n';
std::vector<Version> releases{{2, 0, 0}, {1, 10, 1}, {1, 9, 9}, {1, 10, 0}};
std::sort(releases.begin(), releases.end()); // uses the generated operator<
for (const auto& v : releases) std::cout << v.major << '.' << v.minor << '.' << v.patch << ' ';
std::cout << '\n';
return 0;
}
true true true 1.9.9 1.10.0 1.10.1 2.0.0
A defaulted <=> compares members in declaration order – exactly like comparing words letter by letter. Before C++20 you had to write all six comparison operators by hand.
Subscript and stream output
#include <iostream>
#include <stdexcept>
#include <vector>
class Matrix {
public:
Matrix(int rows, int cols) : rows_(rows), cols_(cols), data_(rows * cols) {}
double& operator()(int r, int c) { return data_.at(r * cols_ + c); } // write access
double operator()(int r, int c) const { return data_.at(r * cols_ + c); } // read access
friend std::ostream& operator<<(std::ostream& os, const Matrix& m) { // friend: can read private data
for (int r = 0; r < m.rows_; r++) {
for (int c = 0; c < m.cols_; c++) os << m(r, c) << (c + 1 < m.cols_ ? " " : "\n");
}
return os;
}
private:
int rows_, cols_;
std::vector<double> data_;
};
int main() {
Matrix m(2, 3);
for (int r = 0; r < 2; r++)
for (int c = 0; c < 3; c++) m(r, c) = (r + 1) * 10 + c;
std::cout << m;
try {
m(5, 0) = 1; // .at() checks bounds
} catch (const std::out_of_range&) {
std::cout << "index out of range\n";
}
return 0;
}
10 11 12 20 21 22 index out of range
The rules of good overloading
| Do | Don't |
|---|---|
| Keep the usual meaning: + adds, == compares | use + to mean "save to disk" |
Return references from +=, =, << so calls can chain | overload &&, || or , (they lose short-circuiting) |
Make operator<< a free (or friend) function | make it a member – it would need the object on the left |
Default <=> and == when member-wise comparison is right | write six comparison operators by hand in C++20 |
Practice
Try it yourself
Write a
Vec2struct with+,==and<<.Show solution
#include <iostream> struct Vec2 { double x = 0, y = 0; bool operator==(const Vec2&) const = default; }; Vec2 operator+(const Vec2& a, const Vec2& b) { return {a.x + b.x, a.y + b.y}; } std::ostream& operator<<(std::ostream& os, const Vec2& v) { return os << '(' << v.x << ", " << v.y << ')'; } int main() { Vec2 a{1, 2}, b{3.5, -1}; std::cout << a + b << ' ' << std::boolalpha << (a + b == Vec2{4.5, 1}) << '\n'; return 0; }(4.5, 1) true
Quick check
Why is operator<< written as a free function?
Its left operand is the stream, not your object.
What does a defaulted <=> do?
Compares members in declaration order and gives you <, <=, > and >=.
What should operator+= return?
A reference to *this, so it can chain like built-in types.
Summary
- Overload operators to give your types natural syntax – keep the usual meanings.
- Write += as a member and + as a free function; default <=> and == in C++20.
- operator<< is a free (often friend) function that returns the stream.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.