Operator overloading
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Operators are just functions
When you write a + b with two integers, the compiler does the addition directly. When a and b are objects of your own class, the compiler looks for a function called operator+. If you write one, a + b calls it. That is all operator overloading is: a function with a special name.
It is worth doing for types that behave like numbers or values, such as money, vectors in geometry, fractions and dates. It is a bad idea for types where the meaning of the operator is not obvious. A + that sends a network request is not a clever design.
A small value type
We will build a two-dimensional point.
#include <iostream>
struct Vec2 {
double x{};
double y{};
Vec2& operator+=(const Vec2& other) {
x += other.x;
y += other.y;
return *this;
}
Vec2 operator-() const { return {-x, -y}; } // unary minus
};
Vec2 operator+(Vec2 a, const Vec2& b) { // non-member
a += b;
return a;
}
Vec2 operator*(const Vec2& v, double k) { return {v.x * k, v.y * k}; }
Vec2 operator*(double k, const Vec2& v) { return v * k; }
bool 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};
Vec2 b{3, 4};
std::cout << a + b << "\n"; // (4, 6)
std::cout << 2.0 * a << "\n"; // (2, 4)
std::cout << -b << "\n"; // (-3, -4)
std::cout << std::boolalpha << (a == Vec2{1, 2}) << "\n"; // true
}
Reading the design
There are a few choices here that I make on purpose.
+=is a member. It changes the left-hand object, so it needs direct access to it, and it returns*thisby reference so calls can chain.+is a free function written in terms of+=. It takes the first argument by value, which is already a copy, modifies it and returns it. You write the real logic once, and the two operators cannot drift apart.*has two overloads so that bothv * 2.0and2.0 * vwork. If it were only a member, the second form would not compile, because the left side is a double.operator<<for streams must be a free function, because the left operand is the stream and you do not own the stream class. It takes and returns the stream by reference so thatcout << a << bchains.
Comparison and the spaceship operator
Before C++20 you had to write six comparison operators by hand. Now you can ask the compiler to generate them all.
#include <compare>
#include <string>
#include <iostream>
struct Version {
int major{};
int minor{};
int patch{};
auto operator<=>(const Version&) const = default; // also gives ==
};
int main() {
Version a{1, 4, 2};
Version b{1, 10, 0};
std::cout << std::boolalpha;
std::cout << (a < b) << "\n"; // true: compares major, then minor, then patch
std::cout << (a == b) << "\n"; // false
}
The defaulted operator<=> compares members in declaration order, and declaring it as defaulted also gives you ==. That is exactly the right behaviour for a version number. If you need a custom order, write the function yourself and return one of std::strong_ordering, std::weak_ordering or std::partial_ordering.
Defaulted comparison is also what lets your type work as a key in std::map and with std::sort with no extra code.
Other useful overloads
The subscript operator lets a class behave like a container. It usually comes in two versions, one for const objects and one for non-const ones.
class Polygon {
public:
void add(Vec2 p) { points_.push_back(p); }
Vec2& operator[](std::size_t i) { return points_[i]; }
const Vec2& operator[](std::size_t i) const { return points_[i]; }
std::size_t size() const { return points_.size(); }
private:
std::vector<Vec2> points_;
};
The call operator operator() turns an object into something you can call like a function. Such objects are called functors, and lambdas are a short way of writing them.
struct Multiplier {
int factor;
int operator()(int x) const { return x * factor; }
};
Multiplier triple{3};
std::cout << triple(14) << "\n"; // 42
Rules I follow
- Keep the usual meaning.
+adds,==tests equality,<<on a stream prints. - If you overload
==you must make!=consistent. In C++20 the compiler derives!=from==for you. - Do not overload
&&,||or the comma operator. You lose short-circuit behaviour, and the result confuses everyone. - Do not overload an operator just because you can. A named function like
distanceTo()is often clearer thanoperator%.
The common mistake
Returning the wrong thing. operator+= should return a reference to the object itself, and operator+ should return a new value by value. Returning a reference to a local variable from operator+ is the same dangling-reference bug we met earlier. Another frequent error is forgetting const on operator== and comparison functions, which then refuse to work on const objects.
Try it yourself
- Write a
Moneyclass holding whole cents in along long, with+,-,==,<and<<printing like12.50. - Add a defaulted
<=>to aDatestruct with year, month and day, and sort a vector of dates. - Write a functor
IsLongerThanthat stores a length and use it withstd::count_ifon a vector of strings.
#include <iostream>
struct Vec2 {
double x{};
double y{};
Vec2& operator+=(const Vec2& other) {
x += other.x;
y += other.y;
return *this;
}
Vec2 operator-() const { return {-x, -y}; } // unary minus
};
Vec2 operator+(Vec2 a, const Vec2& b) { // non-member
a += b;
return a;
}
Vec2 operator*(const Vec2& v, double k) { return {v.x * k, v.y * k}; }
Vec2 operator*(double k, const Vec2& v) { return v * k; }
bool 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};
Vec2 b{3, 4};
std::cout << a + b << "\n"; // (4, 6)
std::cout << 2.0 * a << "\n"; // (2, 4)
std::cout << -b << "\n"; // (-3, -4)
std::cout << std::boolalpha << (a == Vec2{1, 2}) << "\n"; // true
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account