C/C++ Arena

Step 1 of 5

operator+

Built-in types work with operators: a + b, a == b, std::cout << a. C++ lets your types work with them too. This is called operator overloading, and it's why std::string can be joined with + and compared with ==: the standard library overloads those operators.

An operator is just a function with a special name: operator+, operator==, operator<<, and so on. When the compiler sees a + b with your types, it calls operator+(a, b).

#include <iostream>

struct Money {
    long long cents;
};

Money operator+(Money a, Money b) { return {a.cents + b.cents}; }
Money operator*(Money a, int n) { return {a.cents * n}; }
bool operator<(Money a, Money b) { return a.cents < b.cents; }

int main() {
    Money coffee{350};
    Money cake{425};
    Money bill = coffee * 2 + cake;
    long long c = bill.cents % 100;
    std::cout << bill.cents / 100 << "." << (c < 10 ? "0" : "") << c << "\n";   // pad cents to 2 digits
    std::cout << (cake < coffee) << "\n";
}
11.25
0

coffee * 2 + cake reads exactly like math. The usual precedence still applies (* before +), because overloading changes what operators do, not how expressions are parsed.

Guidelines

Your turn: complete operator- and operator* (vector times a number).

Next: operator== and !=