C++ Operator Overloading

You can give the normal operators a meaning for your own classes. This is operator overloading. It makes the code natural, for example a + b for two vectors or two money values.

#include <iostream>

struct Vec2 {
    double x = 0, y = 0;

    Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; }
    Vec2 operator*(double k) const { return {x * k, y * k}; }
    Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; }
    bool operator==(const Vec2&) const = default;                 // C++20: compare all members
};

std::ostream& operator<<(std::ostream& os, const Vec2& v) {       // a non member for <<
    return os << '(' << v.x << ", " << v.y << ')';
}

int main() {
    Vec2 a{1, 2}, b{3, 4};
    std::cout << a + b << '\n';
    std::cout << a * 3 << '\n';
    a += b;
    std::cout << a << ' ' << std::boolalpha << (a == Vec2{4, 6}) << '\n';
}
Output

(4, 6)
(3, 6)
(4, 6) true

The spaceship operator (C++20)

One <=> gives all six comparison operators:

#include <compare>
#include <iostream>

struct Version {
    int major, minor;
    auto operator<=>(const Version&) const = default;
};

int main() {
    Version a{1, 5}, b{2, 0};
    std::cout << std::boolalpha << (a < b) << ' ' << (a == b) << ' ' << (a >= b) << '\n';
}
Output

true false false

The index operator

#include <iostream>
#include <vector>

class Grid {
public:
    explicit Grid(std::size_t n) : data(n, 0) {}
    int& operator[](std::size_t i) { return data[i]; }
    const int& operator[](std::size_t i) const { return data[i]; }
private:
    std::vector<int> data;
};

int main() {
    Grid g(3);
    g[1] = 42;
    std::cout << g[0] << ' ' << g[1] << '\n';
}
Output

0 42

Rules

  • You can not create new operators and can not change the precedence.
  • Some can not be overloaded: ::, ., .*, ?:, sizeof.
  • Keep the normal meaning. + should add, not print.
  • Make operators like == and + const.
Note: Overload an operator only when its meaning is obvious. Otherwise write a named function. Next: C++ Templates.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.