Skip to main content
Be Bitwise
C++Classes & OOP

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

cpp
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:

  1. Precedence first. Overloading never changes precedence, so * still binds tighter than +. The expression groups as a + (b * 2).
  2. b * 2. The left operand is a Vector2D, so the compiler looks for a member operator* that accepts a double. It finds one, and 2 converts from int to double. The call is b.operator*(2.0), with this pointing at b, and it returns a temporary Vector2D(6, 8).
  3. a + temporary. That becomes a.operator+(temporary). The temporary binds to the const Vector2D &other parameter, and the call returns Vector2D(1 + 6, 2 + 8), which is (7, 10).
  4. 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:

cpp
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:

cpp
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.

Key Concept

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.

Try itWrite operator- and operator+= (returning *this by reference), then uncomment the last two asserts.
C++ (GCC 9.2.0)

Subscript Operator

cpp
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:

cpp
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; // 15

Functors 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:

cpp
auto triple = [factor = 3.0](double x) { return x * factor; };
std::cout << triple(5) << std::endl; // 15

For 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-in p && p->ok() never touches p->ok() if p is null. An overloaded operator&& 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 plain operator bool, handle + 1 compiles, because the bool promotes to int. Mark it explicit operator bool() and it still works in if (handle) and while (handle), but stray arithmetic becomes a compile error. That's how std::unique_ptr and the streams do it.
  • operator= has to return *this by reference and survive self-assignment, as you saw with Buffer in 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.

C++ (GCC 9.2.0)