C++ Programming: Objects, RAII and the STL · Classes and Objects

Operator Overloading

Teach your own types to use +, == and << so they read like built-in types.

operator_overloading.cpp

#include <iostream>
using namespace std;

struct Vec {
    int x, y;

    Vec operator+(const Vec &other) const {
        return Vec{x + other.x, y + other.y};
    }

    bool operator==(const Vec &other) const {
        return x == other.x && y == other.y;
    }
};

ostream &operator<<(ostream &out, const Vec &v) {
    return out << "(" << v.x << ", " << v.y << ")";
}

int main() {
    Vec a{1, 2};
    Vec b{3, 4};
    Vec c = a + b;               // calls a.operator+(b)
    bool same = (c == Vec{4, 6});
    cout << c << " " << same << endl;
    return 0;
}

Step by step

  1. a is created on the stack with the value {x: 1, y: 2}.
  2. b is created on the stack with the value {x: 3, y: 4}.
  3. a + b calls a.operator+(b).
  4. A new Vec with the sums: (4, 6).
  5. operator+() has finished, so its variables are gone. The value it returned, {x: 4, y: 6}, is stored in c.
  6. == calls operator==.
  7. The method returns x == other.x && y == other.y.
  8. operator==() has finished, so its variables are gone. The value it returned, true, is stored in same.
  9. C++ calls operator<<(), with out = a char_traits<char> > object and v = → c. It gets its own variables on the stack.
  10. It prints (4, 6).
  11. operator<<() has finished, so its variables are gone.
  12. The method returns 0.
  13. (4, 6) 1.