Operator overloading

Give your own types +, < and <<, and why money is stored in paise.

C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

struct Money {
  long long paise;

  Money operator+(const Money &other) const { return {paise + other.paise}; }
  bool operator<(const Money &other) const { return paise < other.paise; }
};

ostream &operator<<(ostream &out, const Money &m) {
  long long rupees = m.paise / 100, rest = m.paise % 100;
  return out << "Rs " << rupees << "." << (rest < 10 ? "0" : "") << rest;
}

int main() {
  Money fee{150050}, kit{2500};
  cout << fee + kit << "\n";
  cout << (kit < fee) << "\n";

  vector<Money> items = {fee, kit};
  sort(items.begin(), items.end());
  cout << items[0] << "\n";
  return 0;
}
Output
Rs 1525.50
1
Rs 25.00

Money is kept as whole paise in an integer, because a double cannot store 0.1 exactly and small errors add up across a bill. Defining < is enough for sort to work with the new type.

Overload an operator only when its meaning is obvious. + for adding money is clear; + for adding a student to a class is not, so write a named function for that.

โ† Classes and objectsInheritance and virtual functions โ†’