C++ program to overload unary plus (++) operator

//here, operator function is member function
//in prefix manner
//class Currency with Rs and Paisa as private members

#include <iostream>
using namespace std;
class Currency
{
    private:
        int Rs,Paisa;
    public:
        Currency(int r,int p)
        {
            Rs=r;
            Paisa=p;
        }
        Currency()
        {
            Rs=0;
            Paisa=0;
        }
        Currency operator++()
//by member function
        {
            Currency c;
            c.Paisa=++Paisa;
            c.Rs=++Rs;
            if(c.Paisa>=100)
            {
                c.Paisa-=100;
                ++c.Rs;
            }
            return c;
        }
        void display()
        {
            cout<<"Rs. "<<Rs<<" Paisa "<<Paisa;
        }
};
int main()
{
    Currency c1(5,99),c2;
    cout<<endl<<"The entered currency is ";
    c1.display();
    c2=++c1; //same as c2=c1.operator++();
    cout<<endl<<"The incremented currency is ";
    c2.display();
    return 0;
}

No comments:

Post a Comment