WeCodeAcademy

C++ Operator Overloading

You can give your own types the usual operators. This makes a + b work for things like vectors or money.

ExampleC++
#include <iostream>
using namespace std;

struct Vec {
  double x, y;
  Vec operator+(const Vec &o) const { return {x + o.x, y + o.y}; }
  Vec operator*(double k) const { return {x * k, y * k}; }
  bool operator==(const Vec &o) const { return x == o.x && y == o.y; }
};

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

int main() {
  Vec a{1, 2}, b{3, 4};
  cout << a + b << endl;
  cout << a * 3 << endl;
  cout << (a + b == Vec{4, 6}) << endl;
  return 0;
}
Output
(4, 6)
(3, 6)
1
Quick check

What does overloading operator+ allow?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.