C++ Programming: Objects, RAII and the STL · Classes and Objects
Teach your own types to use +, == and << so they read like built-in types.
#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;
}a is created on the stack with the value {x: 1, y: 2}.b is created on the stack with the value {x: 3, y: 4}.operator+() has finished, so its variables are gone. The value it returned, {x: 4, y: 6}, is stored in c.x == other.x && y == other.y.operator==() has finished, so its variables are gone. The value it returned, true, is stored in same.operator<<(), with out = a char_traits<char> > object and v = → c. It gets its own variables on the stack.(4, 6).operator<<() has finished, so its variables are gone.0.