LearnFrenzy
Sign in Take a free test

Static and Friend Members · Static and Friend Programs · Question 5

Money class with symmetric friend operators in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Write a Money class (stored in paise) with an implicit constructor from rupees and hidden-friend operators +, −, ==, < and <<, so that mixed expressions like 100 + m work.

Solution
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>

class Money {
    long long paise_;
public:
    Money(double rupees = 0) : paise_(static_cast<long long>(rupees * 100 + (rupees < 0 ? -0.5 : 0.5))) {}
    friend Money operator+(Money a, Money b) { Money r; r.paise_ = a.paise_ + b.paise_; return r; }
    friend Money operator-(Money a, Money b) { Money r; r.paise_ = a.paise_ - b.paise_; return r; }
    friend bool operator==(Money a, Money b) { return a.paise_ == b.paise_; }
    friend bool operator<(Money a, Money b)  { return a.paise_ < b.paise_; }
    friend std::ostream& operator<<(std::ostream& os, Money m) {
        long long p = m.paise_ < 0 ? -m.paise_ : m.paise_;
        return os << (m.paise_ < 0 ? "-" : "") << "Rs " << p / 100 << '.' << (p % 100 < 10 ? "0" : "") << p % 100;
    }
};

int main() {
    Money rent(12500.50), bill(899.99);
    Money total = rent + bill + 100;            // Money + Money + int
    Money left = 15000 - total;                 // int - Money
    std::vector<Money> v{bill, rent, 50};
    std::sort(v.begin(), v.end());
    std::cout << total << " | " << left << " | " << (bill + 0.01 == 900) << " | "
              << v.front() << ' ' << v.back() << '\n';
    return 0;
}

Output Verified by compiling and running

Rs 13500.49 | Rs 1499.51 | 1 | Rs 50.00 Rs 12500.50

Because the operators are non-member friends, both operands may be converted from numbers: 15000 − total and bill + 0.01 == 900 work. Storing paise avoids floating-point rounding errors in money arithmetic.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links