Operator Overloading
C++ lets you teach operators new tricks for your own types, so a Vector2D adds with + exactly the way an int does.
Basic Operator Overloading
class Vector2D {public: double x, y; Vector2D(double x, double y) : x(x), y(y) {}
Vector2D operator+(const Vector2D &other) const { return Vector2D(x + other.x, y + other.y); }
Vector2D operator*(double scalar) const { return Vector2D(x * scalar, y * scalar); }
bool operator==(const Vector2D &other) const { return x == other.x && y == other.y; }};
Vector2D a(1, 2), b(3, 4);Vector2D c = a + b; // calls operator+Worked Example: What the Compiler Calls
An overloaded operator is a function with an unusual name, and the compiler rewrites each use into an ordinary call. Take a(1, 2) and b(3, 4) and evaluate a + b * 2:
- Precedence first. Overloading never changes precedence, so
*still binds tighter than+. The expression groups asa + (b * 2). b * 2. The left operand is aVector2D, so the compiler looks for a memberoperator*that accepts adouble. It finds one, and2converts frominttodouble. The call isb.operator*(2.0), withthispointing atb, and it returns a temporaryVector2D(6, 8).a + temporary. That becomesa.operator+(temporary). The temporary binds to theconst Vector2D &otherparameter, and the call returnsVector2D(1 + 6, 2 + 8), which is(7, 10).- Cleanup. The temporary from step 2 is destroyed at the end of the full expression.
So a + b * 2 is exactly a.operator+(b.operator*(2.0)), and you're allowed to write it that way, although nobody does.
Predict: does Vector2D c = 2 * a; compile?
No. For a member operator, the left operand has to be the class type, because it becomes this. Here the left operand is 2, an int, and int has no member functions, so the compiler can't use Vector2D::operator*. Multiplication is supposed to commute, so add a free function that flips the arguments and reuses the member:
Vector2D operator*(double s, const Vector2D &v) { return v * s;}Now 2 * a gives (2, 4). That's the general rule of thumb: when either side of a binary operator could be the other type, write it as a free function.
The Stream Operator
To make your type printable with cout:
std::ostream &operator<<(std::ostream &os, const Vector2D &v) { os << "(" << v.x << ", " << v.y << ")"; return os;}
std::cout << c << std::endl; // (4, 6)It's a free function rather than a member, because the left operand here is ostream, not Vector2D.
Returning std::ostream & is what makes chaining work: std::cout << a << " and " << b. Each << hands the stream straight to the next one.
Here's Vector2D with the stream operator wired up and a couple of asserts checking the maths. Add the missing operators until the commented-out checks pass.
Subscript Operator
class Matrix { std::vector<std::vector<double>> data;public: Matrix(int rows, int cols) : data(rows, std::vector<double>(cols, 0.0)) {}
std::vector<double> &operator[](int row) { return data[row]; } const std::vector<double> &operator[](int row) const { return data[row]; }};
Matrix m(3, 3);m[1][2] = 5.0;Function Call Operator
Objects that overload operator() are called functors:
class Multiplier { double factor;public: Multiplier(double f) : factor(f) {} double operator()(double x) const { return x * factor; }};
Multiplier triple(3.0);std::cout << triple(5) << std::endl; // 15Functors can carry state (factor, in this case), which puts them ahead of bare function pointers. They're also what lambdas compile down into. This lambda does the same job:
auto triple = [factor = 3.0](double x) { return x * factor; };std::cout << triple(5) << std::endl; // 15For it, the compiler invents an unnamed class with a double member holding the capture, and a const operator() whose body is the lambda's body. That's Multiplier with the name filed off, and both compile to the same multiply once optimised.
When Not to Overload
Operator overloading should buy you readability, not eat it. Good uses:
- Mathematical types (vectors, matrices, complex numbers)
- Container access (
operator[]) - Comparison operators
- Stream insertion/extraction
A few operators change behaviour in ways that catch people out:
&&and||lose short-circuit evaluation when you overload them. The built-inp && p->ok()never touchesp->ok()ifpis null. An overloadedoperator&&is just a function call, so both operands get evaluated first. Leave these two alone.- Conversion operators such as
operator bool()let the compiler convert your type silently. With a plainoperator bool,handle + 1compiles, because theboolpromotes toint. Mark itexplicit operator bool()and it still works inif (handle)andwhile (handle), but stray arithmetic becomes a compile error. That's howstd::unique_ptrand the streams do it. operator=has to return*thisby reference and survive self-assignment, as you saw withBufferin the constructors and destructors lesson.
Don't overload operators in ways that ambush the reader. operator+ on a string is concatenation, fine. operator+ on a database query means... what, exactly? When the answer isn't obvious, use a named method.
Challenges
Create a base Shape class with a virtual area() method and a Circle subclass.