Tutorials / C++: From Basics to Modern C++ / Operator overloading

Operator overloading

14 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. 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 *this by 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 both v * 2.0 and 2.0 * v work. 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 that cout << a << b chains.

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 than operator%.

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

  1. Write a Money class holding whole cents in a long long, with +, -, ==, < and << printing like 12.50.
  2. Add a defaulted <=> to a Date struct with year, month and day, and sort a vector of dates.
  3. Write a functor IsLongerThan that stores a length and use it with std::count_if on a vector of strings.
cpp
#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