C++ Operator Overloading
C++ lets you define what operators such as +, ==, << or [] mean for your own types. This is called operator overloading. Done well, it makes user-defined types feel as natural as built-in ones: you can add two Vector2 objects with a + b instead of a.add(b). The standard library relies on it everywhere — string uses +, vector uses [], streams use <<.
Overloading an operator
An overloaded operator is just a function with a special name: operator followed by the symbol. It can be a member function or a free function:
#include <iostream>
using namespace std;
struct Vector2 {
double x = 0, y = 0;
Vector2 operator+(const Vector2& other) const { // member: a + b
return {x + other.x, y + other.y};
}
Vector2 operator*(double k) const { // member: v * 2
return {x * k, y * k};
}
Vector2& operator+=(const Vector2& other) { // compound assignment
x += other.x;
y += other.y;
return *this;
}
};
Vector2 operator*(double k, const Vector2& v) { // free: 2 * v
return v * k;
}
int main() {
Vector2 a{1, 2}, b{3, 4};
Vector2 c = a + b;
Vector2 d = 2 * c;
a += b;
cout << c.x << "," << c.y << "\n";
cout << d.x << "," << d.y << "\n";
cout << a.x << "," << a.y << "\n";
}4,6
8,12
4,6
2 * v needs a free function, because for a member operator the left operand must be an object of the class — and 2 is a double.
Printing with operator<<
To make cout << obj work, overload operator<< as a free function that takes and returns an ostream&. Returning the stream is what allows chaining:
#include <iostream>
using namespace std;
class Fraction {
public:
Fraction(int n, int d) : num(n), den(d) { reduce(); }
Fraction operator+(const Fraction& o) const {
return Fraction(num * o.den + o.num * den, den * o.den);
}
Fraction operator*(const Fraction& o) const {
return Fraction(num * o.num, den * o.den);
}
friend ostream& operator<<(ostream& os, const Fraction& f) {
return os << f.num << "/" << f.den;
}
private:
int num, den;
static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
void reduce() {
int g = gcd(num < 0 ? -num : num, den);
num /= g;
den /= g;
}
};
int main() {
Fraction a(1, 2), b(1, 3);
cout << a << " + " << b << " = " << a + b << "\n";
cout << a << " * " << b << " = " << a * b << "\n";
cout << Fraction(6, 8) << "\n";
}1/2 + 1/3 = 5/6
1/2 * 1/3 = 1/6
3/4
Comparison operators and <=>
C++20 makes comparisons easy. Defaulting operator== gives you == and !=; defaulting the three-way comparison ("spaceship") operator<=> gives you <, <=, > and >=, comparing members in declaration order:
#include <iostream>
#include <compare>
#include <vector>
#include <algorithm>
using namespace std;
struct Version {
int major, minor, patch;
auto operator<=>(const Version&) const = default;
bool operator==(const Version&) const = default;
};
int main() {
Version a{1, 4, 2}, b{1, 10, 0}, c{1, 4, 2};
cout << boolalpha;
cout << (a < b) << " " << (a == c) << " " << (b >= c) << "\n";
vector<Version> vs = {{2, 0, 0}, {1, 9, 9}, {1, 10, 1}};
sort(vs.begin(), vs.end()); // uses operator<
for (const auto& v : vs) cout << v.major << "." << v.minor << "." << v.patch << " ";
cout << "\n";
}true true true
1.9.9 1.10.1 2.0.0
Subscript and call operators
operator[] makes an object indexable, and operator() makes it callable like a function (a function object or functor):
#include <iostream>
#include <string>
using namespace std;
class Week {
public:
const string& operator[](int i) const { return days[i % 7]; }
private:
string days[7] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
};
class Multiplier {
public:
explicit Multiplier(int f) : factor(f) {}
int operator()(int x) const { return x * factor; }
private:
int factor;
};
int main() {
Week w;
cout << w[0] << " " << w[4] << " " << w[9] << "\n";
Multiplier triple(3);
cout << triple(7) << " " << triple(10) << "\n";
}Mon Fri Wed
21 30
Rules and guidelines
| Rule | Detail |
|---|---|
| You cannot invent new operators | Only existing ones like +, ==, [] can be overloaded |
| Some cannot be overloaded | ::, ., .*, ?:, sizeof |
| Precedence and arity stay the same | a + b * c still multiplies first |
| At least one operand must be a user-defined type | You cannot redefine int + int |
Tip: Only overload an operator when its meaning is obvious.
+for adding vectors is natural;+for "save to database" is a puzzle for every future reader.
Test yourself
Why must operator<< for printing usually be a free (non-member) function?
- Members cannot return references
- The left operand is the ostream, not your class
- Free functions are faster
- It must be static
What does defaulting operator<=> give you?
- Only ==
- The relational operators <, <=, >, >=
- Addition
- Printing
Which operator can NOT be overloaded?
- []
- ()
- ::
- +=