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
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?