Sunday, June 11, 2017

Operator Overloading II

/*This code was written by A. El-Gadi of Tripoli University for educational purposes. It illustrates input, output, and typecasting operator overloading, as well as forward declaration & postponed implementation. For any questions  and discussion use the comment section below.*/
 
#include<iostream>

using namespace std;

class Cents;//Forward declaration of class Cents

class Dollars{
    private:
        double amount;
    public:
        Dollars():amount(0){};
        Dollars(double am):amount(am){};
        operator double(){return amount;}//Opposite conversion from basic types is not possible
        operator Cents();//Only prototype is possible here, since class Cents definition is incomplete at this stage. We will have to write this operator's implementation after class Cents.
        friend ostream& operator <<(ostream &, Dollars);
        friend istream& operator >>(istream &,Dollars &);
    };

ostream& operator <<(ostream &out, Dollars d){
            out<<'$'<<d.amount;
            return out;
            }

istream& operator >>(istream &in,Dollars &d){ in>>d.amount; return in;}//Input operator has not been covered in this term.

class Cents{
    private:
        double amount;
    public:
        Cents():amount(0){};
        Cents(double am):amount(am){};
        operator double(){return amount;}//Opposite conversion from basic types is not possible
        operator Dollars(){return Dollars(amount/100);}
        friend ostream& operator <<(ostream &, Cents);
        friend istream& operator >>(istream &,Cents &);
    };

ostream& operator <<(ostream &out, Cents c){
            out<<c.amount;
            return out;
            }

istream& operator >>(istream &in,Cents &c){ in>>c.amount; return in;}

   
Dollars::operator Cents(){return Cents(amount*100);}


int main(){
Dollars d1(5.3221),d2;

cout<<d1<<endl;
cout<<d1<<endl;

Dollars d3,d4;
d3=d4;

cout<<d3<<endl;

cout<<d1<<endl;
cin>>d3>>d4;
cout<<d3<<' '<<d4<<endl;

Cents c1(400),c2;
c2=d3;

cout<<c1<<' '<<c2<<endl;
d4=c1;
cout<<d4;

return 0;
}

2 comments:

  1. doctor, why we use operator double() ?

    ReplyDelete
    Replies
    1. So we can assign Dollars directly to doubles and pass Dollars to functions that accept double.
      Example 1:
      Dollars dol(1.5); double dub;
      dub=dol;//This assignment is possible because we have overloaded the operator double()

      Example 2:
      double timesten(double x){return 10*x;}
      int main(){Dollars dol(1.75); double xx;
      xx=timesten(dol)//The function call with Dollars as a parameter is possible because we have overloaded the operator double().}

      In other words Dollars becomes convertible to double.

      I hope this helps

      Delete