LearnFrenzy
Sign in Take a free test

Encapsulation · Encapsulation Programs · Question 4

An immutable Money value type in C++ Solution, output & explanation

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

Write an immutable Money class (amount in paise and a currency) whose operations return new objects, refuse to mix currencies, and allocate an amount into equal parts without losing paise.

Solution
main.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

class Money {
    long long paise_;
    std::string cur_;
public:
    Money(long long paise, std::string cur) : paise_(paise), cur_(std::move(cur)) {}
    Money operator+(const Money& o) const {
        if (cur_ != o.cur_) throw std::invalid_argument("currency mismatch");
        return {paise_ + o.paise_, cur_};
    }
    std::vector<Money> split(int parts) const {
        std::vector<Money> out;
        for (int i = 0; i < parts; ++i)                         // spread the remainder over the first parts
            out.emplace_back(paise_ / parts + (i < paise_ % parts ? 1 : 0), cur_);
        return out;
    }
    std::string str() const {
        return cur_ + " " + std::to_string(paise_ / 100) + "." + (paise_ % 100 < 10 ? "0" : "") + std::to_string(paise_ % 100);
    }
};

int main() {
    const Money bill(100000, "INR"), tip(5000, "INR");
    Money total = bill + tip;
    for (const Money& share : total.split(3)) std::cout << share.str() << " | ";
    std::cout << '\n' << bill.str() << '\n';
    try { Money x = bill + Money(1000, "USD"); }
    catch (const std::invalid_argument& e) { std::cout << e.what() << '\n'; }
    return 0;
}

Output Verified by compiling and running

INR 350.00 | INR 350.00 | INR 350.00 | 
INR 1000.00
currency mismatch

No member function changes an existing Money, so bill and tip can be shared safely. split hands the leftover paise to the first shares, so the parts always add up exactly to the total.

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