Overload operators for a Money class

Description: Write a class Money which keeps rupees and paise. Overload +, == and <<. Add Rs. 10.75 and Rs. 5.50, and print Rs. 16.25.

Hint:

  • Keep the value in paise (a whole number) to avoid decimal errors.

Solution

#include <iostream>

class Money {
public:
    explicit Money(long long paise) : paise(paise) {}
    Money operator+(const Money& o) const { return Money(paise + o.paise); }
    bool operator==(const Money&) const = default;
    friend std::ostream& operator<<(std::ostream& os, const Money& m) {
        return os << "Rs. " << m.paise / 100 << '.' << (m.paise % 100 < 10 ? "0" : "") << m.paise % 100;
    }
private:
    long long paise;
};

int main() {
    Money a(1075), b(550);
    std::cout << a + b << '\n';
    std::cout << std::boolalpha << (a + b == Money(1625)) << '\n';
}
Output

Rs. 16.25
true

How it works

  • Money is kept as a whole number of paise, so there is no decimal rounding problem.
  • operator<< is a friend function, because the stream is on the left side.

Read Operator Overloading.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.