LearnFrenzy
Sign in Take a free test

Operator Overloading · Operator Overloading Programs · Question 7

Money class with safe arithmetic and GST in C++ Solution, output & explanation

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

Write a Money class (stored in paise) with +, -, * by an integer quantity, a percent() helper, comparisons and operator<<; build a bill with items, GST and a discount.

Solution
main.cpp
#include <compare>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

class Money {
    long p_;
public:
    explicit constexpr Money(long paise = 0) : p_(paise) {}
    static constexpr Money rupees(long r) { return Money(r * 100); }
    Money& operator+=(Money o) { p_ += o.p_; return *this; }
    friend Money operator+(Money a, Money b) { return a += b; }
    friend Money operator-(Money a, Money b) { return Money(a.p_ - b.p_); }
    friend Money operator*(Money a, int q) { return Money(a.p_ * q); }
    Money percent(int pct) const { return Money((p_ * pct + 50) / 100); }   // rounded to the nearest paisa
    auto operator<=>(const Money&) const = default;
    friend std::ostream& operator<<(std::ostream& os, Money m) {
        return os << "Rs " << m.p_ / 100 << '.' << std::setfill('0') << std::setw(2) << m.p_ % 100 << std::setfill(' ');
    }
};

int main() {
    struct Item { std::string name; Money price; int qty; };
    std::vector<Item> cart{{"Pen", Money(2550), 4}, {"Bag", Money::rupees(899), 1}, {"Tape", Money(4999), 2}};
    Money subtotal;
    for (const auto& i : cart) subtotal += i.price * i.qty;
    Money gst = subtotal.percent(18);
    Money discount = subtotal > Money::rupees(1000) ? subtotal.percent(5) : Money();
    std::cout << "subtotal " << subtotal << "\ngst      " << gst << "\ndiscount " << discount
              << "\ntotal    " << subtotal + gst - discount << '\n';
    return 0;
}

Output Verified by compiling and running

subtotal Rs 1100.98
gst      Rs 198.18
discount Rs 55.05
total    Rs 1244.11

Integer paise avoid floating-point errors, and the explicit constructor stops raw numbers from silently becoming money. The comparison comes from a defaulted <=>.

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