Operator Overloading
C++ lets you define what an operator like + means for your own type, by implementing a method named operator+. This is genuinely distinctive compared to every other course on this site: Python has dunder methods for a similar purpose, but no other language here lets a type opt into the exact same operator syntax built-in numeric types use.
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
Point operator+(const Point& other) const {
return Point(x + other.x, y + other.y);
}
};
int main() {
Point a(1, 2);
Point b(3, 4);
Point c = a + b;
cout << "(" << c.x << ", " << c.y << ")" << endl;
return 0;
}(4, 6)
a + b calls a.operator+(b) behind the scenes — the syntax reads exactly like adding two numbers, even though Point is a type you defined. The : x(x), y(y) syntax in the constructor is a member initializer list, the idiomatic way to set a C++ class's fields directly from its constructor parameters.
Next: templates — C++'s own compile-time mechanism for writing one function or class that works across many types.
Practice exercise
Define a class Vec2 with int x, y and a constructor. Overload operator+ so that adding two Vec2s adds their components. Add Vec2(2, 3) and Vec2(4, 1), then print the result's x and y separated by a space.