Tsallaka zuwa abun ciki
Justice Tech School

Operator Overloading

Define + and << for your types to make them natural to use.

Example
#include <iostream>

struct V { int x, y; };
V operator+(V a, V b) { return {a.x + b.x, a.y + b.y}; }
std::ostream &operator<<(std::ostream &o, V v) { return o << "(" << v.x << "," << v.y << ")"; }

int main() {
  V a{1, 2}, b{3, 4};
  std::cout << (a + b) << "\n";
  return 0;
}

Result

(4,6)

Exercise

Overload keyword.

V +(V a, V b)

Quiz Test

What can be overloaded?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.