You are on page 1of 54

1.

Increment counter variable with ++ operator:


#include<iostream>

using namespace std

class Counter

private:

unsigned int count;

public:

Counter():count(0)

{ }

unsigned int get_count()

{ return count; }

void operator ++ ()

++count;

};

int main()

Counter c1,c2;

cout<<"\nc1="<< c1.get_count();

cout<<"\nc2="<<c2.get_count();

++c1;

++c2;

++c2;

cout<<"\nc1="<< c1.get_count();

cout<<"\nc2="<<c2.get_count()<<endl;

return 0;

OPERATOR OVERLOADING 1
2. Increment counter variable with ++ operator, return value:
#include<iostream>

using namespace std;

class Counter

private:

unsigned int count;

public:

Counter():count(0)

{ }

unsigned int get_count()

{ return count; }

Counter operator ++ ()

++count;

Counter temp;

temp.count=count;

return temp;

};

int main()

Counter c1,c2;

cout<<"\nc1="<<c1.get_count();

cout<<"\nc2="<<c2.get_count();

++c1;

c2=++c1;

cout<<"\nc1="<<c1.get_count();

cout<<"\nc2="<<c2.get_count()<<endl;

return 0;

OPERATOR OVERLOADING 2
3. Increment counter variable with ++ operator :
#include<iostream>

using namespace std;

class Counter

private:

unsigned int count;

public:

Counter():count(0)

{ }

Counter(int c):count(c)

{ }

unsigned int get_count()

{ return count; }

Counter operator ++ ()

++count;

return Counter(count);

};

int main()

Counter c1,c2;

cout<<"\nc1="<<c1.get_count();

cout<<"\nc2="<<c2.get_count();

++c1;

c2=++c1;

cout<<"\nc1="<<c1.get_count();

cout<<"\nc2="<<c2.get_count()<<endl;

return 0;

OPERATOR OVERLOADING 3
4. Overloaded ++ operator in both prefix and postfix :
#include<iostream>

using namespace std;

class Counter

private:

unsigned int count;

public:

Counter():count(0)

{ }

Counter(int c):count(c)

{ }

unsigned int get_count() const

{ return count; }

Counter operator ++ ()

return Counter(++count);

Counter operator ++ (int)

return Counter(count++);

};

OPERATOR OVERLOADING 4
int main()

Counter c1,c2;

cout<<"\nc1="<<c1.get_count();

cout<<"\nc2="<<c2.get_count();

++c1;

c2=++c1;

cout<<"\nc1="<<c1.get_count();

cout<<"\nc2="<<c2.get_count();

c2=c1++;

cout<<"\nc1="<<c1.get_count();

cout<<"\nc2="<<c2.get_count()<<endl;

return 0;

OPERATOR OVERLOADING 5
5. Overloaded ‘+’ operator adds two Distances:
#include<iostream>

using namespace std;

class Distance

private:

int feet;

float inches;

public:

Distance():feet(0),inches(0.0)

{ }

Distance(int ft,float in):feet(ft),inches(in)

{ }

void getdist()

cout<<"\nEnter feet: "; cin>>feet;

cout<<"Enter inches: "; cin>>inches;

void showdist() const

{ cout<<feet<<"\’-"<<inches<<"\”"; }

Distance operator+( Distance ) const;

};

Distance Distance::operator+(Distance d2) const

int f=feet+d2.feet;

float i=inches+d2.inches;

if(i>=12.0)

i-=12.0;

f++;

return Distance(f,i);

OPERATOR OVERLOADING 6
int main()

Distance dist1,dist3,dist4;

dist1.getdist();

Distance dist2(11,6.25);

dist3=dist1+dist2;

dist4=dist1+dist2+dist3;

cout<<"dist1 = "; dist1.showdist(); cout<<endl;

cout<<"dist2 = "; dist2.showdist(); cout<<endl;

cout<<"dist2 = "; dist3.showdist(); cout<<endl;

cout<<"dist4 = "; dist4.showdist(); cout<<endl;

return 0;

OPERATOR OVERLOADING 7
6. Overloaded ‘+’ operator concatenates strings:
#include<iostream>

#include<string.h>

#include<stdlib.h>

using namespace std;

class String

private:

enum { SZ=80 };

char str[SZ];

public:

String()

{ strcpy(str, “”); }

String( char s[] )

{ strcpy(str, s); }

void display() const

{ cout<<str; }

String operator+(String ss) const

String temp;

if( strlen(str)+strlen(ss.str)<SZ )

strcpy(temp.str,str);

strcat(temp.str,ss.str);

else

{ cout<<“\nString overflow”; exit(1); }

return temp;

};

OPERATOR OVERLOADING 8
int main()

String s1="\nMerry Christmas! ";

String s2="Happy new year!";

String s3;

s1.display();

s2.display();

s3.display();

s3=s1+s2;

s3.display();

cout<<endl;

return 0;

OPERATOR OVERLOADING 9
7. Overloaded ‘<’ operator compares two Distances:
#include<iostream>

using namespace std;

class Distance

private:

int feet;

float inches;

public:

Distance():feet(0),inches(0.0)

{ }

Distance(int ft,float in):feet(ft),inches(in)

{ }

void getdist()

cout<<"\nEnter feet: "; cin>>feet;

cout<<"Enter inches: "; cin>>inches;

void showdist() const

{ cout<<feet<<"\’-"<<inches<<"\”"; }

bool operator<(Distance) const;

};

bool Distance::operator<(Distance d2) const

float bf1=feet+inches/12;

float bf2=d2.feet+d2.inches/12;

return(bf1<bf2)?true:false;

OPERATOR OVERLOADING 10
int main()

Distance dist1;

dist1.getdist();

Distance dist2(6,2.5);

cout<<"\ndist1 = "; dist1.showdist();

cout<<"\ndist2 = "; dist2.showdist();

if( dist1<dist2 )

cout<<"\ndist1 is less than dist2";

else

cout<<"\ndist1 is greater than (or equal to) dist2";

cout<<endl;

return 0;

OPERATOR OVERLOADING 11
8. Overloaded ‘==’ operator compares strings:
#include<iostream>

#include<string.h>

using namespace std;

class String

private:

enum { SZ=80 };

char str[SZ];

public:

String()

{ strcpy(str,“”); }

String( char s[] )

{ strcpy(str,s); }

void display() const

{ cout<<str; }

void getstr()

{ cin.get(str,SZ); }

bool operator==(String ss) const

return( strcmp(str,ss.str)==0 ) ?true:false;

};

OPERATOR OVERLOADING 12
int main()

String s1="yes";

String s2="no";

String s3;

cout<<"\nEnter ‘yes’ or ‘no’: ";

s3.getstr();

if(s3==s1)

cout<<"You typed yes\n";

elseif(s3==s2)

cout<<"You typed no\n";

else

cout<<"You didn’t follow instructions\n";

return 0;

OPERATOR OVERLOADING 13
9. Overloaded ‘+=’ assignment operator:
#include<iostream>

using namespace std;

class Distance

private:

int feet;

float inches;

public:

Distance():feet(0),inches(0.0)

{ }

Distance(int ft,float in):feet(ft),inches(in)

{ }

void getdist()

cout<<"\nEnter feet: "; cin>>feet;

cout<<"Enter inches: "; cin>>inches;

void showdist() const

{ cout<<feet<<"\’-"<<inches<<"\”"; }

void operator+=( Distance );

};

void Distance::operator+=(Distance d2)

feet+=d2.feet;

inches+=d2.inches;

if(inches>=12.0)

inches-=12.0;

feet++;

OPERATOR OVERLOADING 14
int main()

Distance dist1;

dist1.getdist();

cout<<"\ndist1 = "; dist1.showdist();

Distance dist2(11,6.25);

cout<<"\ndist2 = "; dist2.showdist();

dist1+=dist2;

cout<<"\nAfter addition,";

cout<<"\ndist1 = "; dist1.showdist();

cout<<endl;

return 0;

OPERATOR OVERLOADING 15
10. Creates safe array, uses separate put and get functions:
#include<iostream>

#include<process.h>

using namespace std;

const int LIMIT=100;

class safearay

private:

int arr[LIMIT];

public:

void putel(int n,int elvalue)

if(n<0||n>=LIMIT)

{ cout<<"\nIndex out of bounds"; exit(1); }

arr[n]=elvalue;

int getel(int n) const

if(n<0||n>=LIMIT)

{ cout<<"\nIndex out of bounds"; exit(1); }

return arr[n];

};

OPERATOR OVERLOADING 16
int main()

safearay sa1;

for(int j=0; j<LIMIT; j++)

sa1.putel(j, j*10);

for(j=0; j<LIMIT; j++)

int temp=sa1.getel(j);

cout<<"Element "<<j<<" is "<<temp<<endl;

return 0;

OPERATOR OVERLOADING 17
11. Uses one access() function for both put and get:
#include<iostream>

#include<process.h>

using namespace std;

const int LIMIT=100;

class safearay

private:

int arr[LIMIT];

public:

int& access(int n)

if(n<0||n>=LIMIT )

{ cout<<"\nIndex out of bounds"; exit(1); }

return arr[n];

};

int main()

safearay sa1;

for(int j=0; j<LIMIT; j++)

sa1.access(j)=j*10;

for(j=0; j<LIMIT; j++)

int temp=sa1.access(j);

cout<<"Element "<<j<<" is "<<temp<<endl;

return 0;

OPERATOR OVERLOADING 18
12. Uses overloaded [] operator for both put and get:
#include<iostream>

#include<process.h>

using namespace std;

const int LIMIT=100;

class safearay

private:

int arr[LIMIT];

public:

int& operator [](int n)

if(n<0||n>=LIMIT)

{ cout<<"\nIndex out of bounds"; exit(1); }

return arr[n];

};

int main()

safearay sa1;

for(int j=0; j<LIMIT; j++) //insert elements

sa1[j] = j*10; //*left* side of equal sign

for(j=0; j<LIMIT; j++) //display elements

int temp=sa1[j];

cout<<"Element "<<j<<" is "<<temp<<endl;

return 0;

OPERATOR OVERLOADING 19
13. Distance to meters, meters to Distance:
#include<iostream>

using namespace std;

class Distance

private:

const float MTF;

int feet;

float inches;

public:

Distance():feet(0),inches(0.0),MTF(3.280833F)

{ }

Distance(float meters):MTF(3.280833F)

float fltfeet=MTF*meters;

feet=int(fltfeet);

inches=12*(fltfeet-feet);

Distance(int ft,float in):feet(ft),

inches(in),MTF(3.280833F)

{ }

void getdist()

cout<<"\nEnter feet: "; cin>>feet;

cout<<"Enter inches: "; cin>>inches;

void showdist() const

{ cout<<feet<<"\’-"<<inches<<"\”"; }

operator float() const

float fracfeet=inches/12;

fracfeet+=static_cast<float>(feet);

return fracfeet/MTF;

OPERATOR OVERLOADING 20
};

int main()

float mtrs;

Distance dist1=2.35F;

cout<<"\ndist1 = "; dist1.showdist();

mtrs=static_cast<float>(dist1);

cout<<"\ndist1 = "<<mtrs<<" meters\n";

Distance dist2(5,10.25);

mtrs=dist2;

cout<<"\ndist2 = "<<mtrs<<" meters\n";

return 0;

OPERATOR OVERLOADING 21
14. Convert between ordinary strings and class String :
#include<iostream>

#include<string.h>

using namespace std;

class String

private:

enum { SZ=80 };

char str[SZ];

public:

String()

{ str[0]=‘\0’; }

String( char s[] )

{ strcpy(str, s); }

void display() const

{ cout << str; }

operator char*()

{ return str; }

};

int main()

String s1;

char xstr[] = "Joyeux Noel! ";

s1 = xstr;

s1.display();

String s2 = "Bonne Annee!";

cout<<static_cast<char*>(s2);

cout<<endl;

return 0;

OPERATOR OVERLOADING 22
15. Creates a class name ‘scrollbar’:
#include<iostream>

#include<string>

using namespace std;

class scrollbar

private:

int size;

mutable string owner;

public:

scrollbar(int sz,string own):size(sz),owner(own)

{ }

void setSize(int sz)

{ size = sz; }

void setOwner(string own) const

{ owner = own; }

int getSize() const

{ return size; }

string getOwner() const

{ return owner; }

};

int main()

const scrollbar sbar(60,"Window1");

sbar.setOwner(“Window2”);

cout<<sbar.getSize()<<", "<<sbar.getOwner()<<endl;

return 0;

OPERATOR OVERLOADING 23
Exercise:
1. Write a program that substitutes an overloaded += operator for the overloaded +
operator in the STRPLUS program in this chapter.
#include<iostream>

using namespace std;

class Distance

private:

int feet:

float inches;

public:

Distance();

Distance(int f,int i);

int getFeet() const { return feet; }

void setFeet(int f) { feet = f; }

int getInches() const { return inches; }

void setInches(int i) { inches = i; }

void display() const

cout<<feet<<" ft, "<<inches<<" in"<<endl;

Distance operator+(const Distance& other) const

int new_feet=feet+other.feet;

int new_inches=inches+other.inches;

if(new_inches>=12)

new_feet+=1;

new_inches-=12;

return Distance(new_feet, new_inches);

OPERATOR OVERLOADING 24
Distance operator-(const Distance& other) const

int new_feet=feet-other.feet;

int new_inches=inches-other.inches;

if(new_inches<0)

new_feet-=1;

new_inches+=12;

return Distance(new_feet, new_inches);

};

Distance::Distance():feet(0),inches(0) {}

Distance::Distance(int f,int i):feet(f),inches(i) {}

int main()

Distance dist1(5,6);

Distance dist2(3,8);

Distance dist3=dist1+dist2;

cout<<"dist1 + dist2 = ";

dist3.display();

Distance dist4=dist1-dist2;

cout<<"dist1 - dist2 = ";

dist4.display();

return 0;

OPERATOR OVERLOADING 25
2. Write a program that substitutes an overloaded += operator for the overloaded +
operator in the STRPLUS program in this chapter.
#include<iostream>

#include<cstring>

using namespace std;

class MyString

private:

char* str;

public:

MyString(const char* s)

str=new char[strlen(s)+1];

strcpy(str,s);

MyString& operator+=(const MyString& other)

char* temp=new char[strlen(str)+strlen(other.str)+1];

strcpy(temp,str);

strcat(temp,other.str);

delete[] str;

str=temp;

return*this;

friend ostream& operator<<(ostream& os,const MyString& myStr)

os<<myStr.str;

return os;

~MyString()

delete[] str;

};

OPERATOR OVERLOADING 26
int main()

MyString s1("Hello,");

MyString s2("world!");

MyString s3("Concatenation:");

s1+=s2;

cout<<"s1:"<<s1<<endl;

s3=s1+=s2;

cout<<"s3:"<<s3<<endl;

return 0;

OPERATOR OVERLOADING 27
3. Modify the time class from Exercise 3 in Chapter 6 so that instead of a function
add_time() it uses the overloaded + operator to add two times. Write a program to
test this class.
#include<iostream>

using namespace std;

class Time

private:

int hours;

int minutes;

public:

Time():hours(0),minutes(0) {}

Time(int h,int m) : hours(h),minutes(m) {}

void display() const

cout<<hours<<" hours and "<<minutes<<" minutes";

Time operator+(const Time& other) const

int totalHours=hours+other.hours;

int totalMinutes=minutes+other.minutes;

if (totalMinutes>=60)

totalHours+=totalMinutes/60;

totalMinutes%=60;

return Time(totalHours,totalMinutes);

};

OPERATOR OVERLOADING 28
int main()

Time time1(3,45);

Time time2(2,30);

Time sum=time1+time2;

cout<<"Time 1: ";

time1.display();

cout<<endl;

cout<<"Time 2: ";

time2.display();

cout<<endl;

cout<<"Sum of Time 1 and Time 2: ";

sum.display();

cout<<endl;

return 0;

OPERATOR OVERLOADING 29
4. Create a class Int based on Exercise 1 in Chapter 6. Overload four integer arithmetic
operators (+, -, *, and /) so that they operate on objects of type Int.
#include<iostream>

#include<limits>

using namespace std;

class Int

private:

long double value;

public:

Int(long double val):value(val) {}

Int operator+(const Int& other) const

long double result=value+other.value;

checkOverflow(result);

return Int(result);

Int operator-(const Int& other) const

long double result=value-other.value;

checkOverflow(result);

return Int(result);

Int operator*(const Int& other) const

long double result=value*other.value;

checkOverflow(result);

return Int(result);

Int operator/(const Int& other) const

OPERATOR OVERLOADING 30
{

if(other.value==0)

cerr<<"Error: Division by zero!"<<endl;

exit(1);

long double result=value/other.value;

checkOverflow(result);

return Int(result);

void display() const

cout<<value;

private:

void checkOverflow(long double result) const

if(result>numeric_limits<int>::max()||result<numeric_li mits<int>::min())

cerr<<"Warning: Arithmetic overflow detected! Program


terminated."<<endl;

exit(1);

};

OPERATOR OVERLOADING 31
int main()

Int a(2147483647);

Int b(2);

Int sum=a+b;

cout<<"a + b = ";

sum.display();

cout<<endl;

Int diff=a-b;

cout<<"a - b = ";

diff.display();

cout<<endl;

Int product=a*b;

cout<<"a * b = ";

product.display();

cout<<endl;

Int quotient=a/b;

cout<<"a / b = ";

quotient.display();

cout<<endl;

return 0;

OPERATOR OVERLOADING 32
5. Augment the time class referred to in Exercise 3 to include overloaded increment
(++) and decrement (--) operators that operate in both prefix and postfix notation
and return values. Add statements to main() to test these operators.
#include<iostream>

using namespace std;

class Time

private:

int hours;

int minutes;

public:

Time():hours(0),minutes(0) {}

Time(int h,int m):hours(h),minutes(m) {}

void display() const

cout<<hours<<" hours and "<<minutes<<" minutes";

Time& operator++()

minutes++;

if(minutes>=60)

minutes-=60;

hours++;

if(hours>=24)

hours=0;

return *this;

Time operator++(int)

OPERATOR OVERLOADING 33
Time temp(hours,minutes);

operator++();

return temp;

Time& operator--()

if(minutes==0)

if(hours==0)

hours=23;

else

hours--;

minutes=59;

else

minutes--;

return *this;

Time operator--(int)

Time temp(hours,minutes);

operator--();

return temp;

};

OPERATOR OVERLOADING 34
int main()

Time time(9,30);

cout<<"Initial Time: ";

time.display();

cout<<endl;

++time;

cout<<"After Prefix Increment: ";

time.display();

cout<<endl;

Time temp1=time++;

cout<<"After Postfix Increment: ";

time.display();

cout<<endl;

cout<<"Postfix Increment Result: ";

temp1.display();

cout<<endl;

--time;

cout<<"After Prefix Decrement: ";

time.display();

cout<<endl;

Time temp2=time--;

cout<<"After Postfix Decrement: ";

time.display();

cout<<endl;

cout<<"Postfix Decrement Result: ";

temp2.display();

cout<<endl;

return 0;

OPERATOR OVERLOADING 35
6. Add to the time class of Exercise 5 the ability to subtract two time values using
the overloaded (-) operator, and to multiply a time value by a number of type float,
using the overloaded (*) operator.
#include<iostream>

using namespace std;

class Time

private:

int hours;

int minutes;

public:

Time():hours(0),minutes(0) {}

Time(int h,int m):hours(h),minutes(m) {}

void display() const

cout<<hours<<" hours and "<<minutes<<" minutes";

Time operator-(const Time& other) const

int totalMinutes1=hours*60+minutes;

int totalMinutes2=other.hours*60+other.minutes;

int differenceMinutes=totalMinutes1-totalMinutes2;

if(differenceMinutes<0)

differenceMinutes+=24*60;

int resultHours=differenceMinutes/60;

int resultMinutes=differenceMinutes%60;

return Time(resultHours, resultMinutes);

OPERATOR OVERLOADING 36
Time operator*(float factor) const

int totalMinutes=hours*60+minutes;

totalMinutes=static_cast<int>(totalMinutes*factor);

int resultHours=totalMinutes/60;

int resultMinutes=totalMinutes%60;

return Time(resultHours,resultMinutes);

};

int main()

Time time1(9,30);

Time time2(2,45);

cout<<"Time 1: ";

time1.display();

cout<<endl;

cout<<"Time 2: ";

time2.display();

cout<<endl;

Time difference=time1-time2;

cout<<"Time 1 - Time 2: ";

difference.display();

cout<<endl;

Time product=time1*1.5;

cout<<"Time 1 * 1.5: ";

product.display();

cout<<endl;

return 0;

OPERATOR OVERLOADING 37
7. Modify the fraction class in the four-function fraction calculator from Exercise 11
in Chapter 6 so that it uses overloaded operators for addition, subtraction,
multiplication, and division.
#include<iostream>

using namespace std;

class Fraction

private:

int numerator;

int denominator;

int gcd(int a,int b) const

if(b==0)

return a;

return gcd(b,a%b);

void reduce()

int common=gcd(numerator,denominator);

numerator/=common;

denominator/=common;

public:

Fraction(int num,int den):numerator(num),denominator(den)

if(denominator==0)

cerr<<"Error: Denominator cannot be zero!"<<endl;

exit(1);

reduce();

OPERATOR OVERLOADING 38
Fraction operator+(const Fraction& other) const

int
newNumerator=(numerator*other.denominator)+(other.numerator*denominator);

int newDenominator=denominator*other.denominator;

return Fraction(newNumerator,newDenominator);

Fraction operator-(const Fraction& other) const

int newNumerator=(numerator*other.denominator)-
(other.numerator*denominator);

int newDenominator=denominator*other.denominator;

return Fraction(newNumerator,newDenominator);

Fraction operator*(const Fraction& other) const

int newNumerator=numerator*other.numerator;

int newDenominator=denominator*other.denominator;

return Fraction(newNumerator,newDenominator);

Fraction operator/(const Fraction& other) const

if(other.numerator==0)

cerr<<"Error: Division by zero!"<<endl;

exit(1);

int newNumerator=numerator*other.denominator;

int newDenominator=denominator*other.numerator;

return Fraction(newNumerator,newDenominator);

OPERATOR OVERLOADING 39
bool operator==(const Fraction& other) const

return (numerator==other.numerator)&&(denominator==other.denominator);

bool operator!=(const Fraction& other) const

return !(*this==other);

void display() const

cout<<numerator<<"/"<<denominator;

};

int main()

Fraction frac1(3,4);

Fraction frac2(1,2);

cout<<"Fraction 1: ";

frac1.display();

cout<<endl;

cout<<"Fraction 2: ";

frac2.display();

cout<<endl;

Fraction sum=frac1+frac2;

cout<<"Fraction 1 + Fraction 2: ";

sum.display();

cout<<endl;

Fraction diff=frac1-frac2;

cout<<"Fraction 1 - Fraction 2: ";

OPERATOR OVERLOADING 40
diff.display();

cout<<endl;

Fraction product=frac1*frac2;

cout<<"Fraction 1 * Fraction 2: ";

product.display();

cout<<endl;

Fraction quotient=frac1/frac2;

cout<<"Fraction 1 / Fraction 2: ";

quotient.display();

cout<<endl;

if(frac1==frac2)

cout<<"Fraction 1 is equal to Fraction 2."<<endl;

else

cout<<"Fraction 1 is not equal to Fraction 2."<<endl;

if(frac1!=frac2)

cout<<"Fraction 1 is not equal to Fraction 2."<<endl;

else

cout<<"Fraction 1 is equal to Fraction 2."<<endl;

return 0;

OPERATOR OVERLOADING 41
8. Modify the bMoney class from Exercise 12 in Chapter 7, “Arrays and Strings”:

#include<iostream>

#include<string>

#include<sstream>

using namespace std;

class bMoney

private:

long double money;

long double strToLongDouble(const string& str)

istringstream iss(str);

long double result;

iss>>result;

return result;

public:

explicit bMoney(const string& str):money(strToLongDouble(str)) {}

bMoney():money(0.0) {}

bMoney operator+(const bMoney& other) const

return bMoney(money+other.money);

bMoney operator-(const bMoney& other) const

return bMoney(money-other.money);

bMoney operator*(long double value) const

return bMoney(money*value);

OPERATOR OVERLOADING 42
long double operator/(const bMoney& other) const

if (other.money==0.0)

cerr<<"Error: Division by zero!"<<endl;

exit(1);

return money/other.money;

bMoney operator/(long double value) const

if(value==0.0)

scerr<<"Error: Division by zero!"<<endl;

exit(1);

return bMoney(money/value);

void display() const

cout<<"$"<<money;

};

int main()

string input1,input2;

long double pricePerWidget;

while (true)

OPERATOR OVERLOADING 43
cout<<"Enter the first money amount (e.g., $12345.67): ";

cin>>input1;

if(input1=="0/1"||input1=="0/1")

cout<<"Exiting the program."<<endl;

break;

cout<<"Enter the second money amount: ";

cin>>input2;

cout<<"Enter the price per widget: ";

cin>>pricePerWidget;

bMoney money1(input1);

bMoney money2(input2);

bMoney sum=money1+money2;

bMoney difference=money1-money2;

bMoney product=money1*pricePerWidget;

long double division1= money1/money2;

bMoney division2=money1/pricePerWidget;

cout<<"Sum: ";

sum.display();

cout<<"Difference: ";

difference.display();

cout<<endl;

cout<<"Product: ";

product.display();

cout<<"Division (money1 / money2): "<<division1<<endl;

cout<<"Division (money1 / pricePerWidget): ";

division2.display();

return 0;

OPERATOR OVERLOADING 44
9. Augment the safearay class in the ARROVER3 program in this chapter so that the user
can specify both the upper and lower bound of the array (indexes running from 100
to 200, for example). Have the overloaded subscript operator check the index each
time the array is accessed to ensure that it is not out of bounds.
#include<iostream>

using namespace std;

class safearay

private:

static const int LIMIT=100;

int arr[LIMIT];

int lowerBound;

int upperBound;

public:

safearay(int lower,int upper):lowerBound(lower),upperBound(upper)

if(lowerBound>upperBound)

cerr<<"Error: Lower bound cannot be greater than upper


bound!"<<endl;

exit(1);

int& operator[](int index)

if(index<lowerBound||index>upperBound)

cerr<<"Error: Index out of bounds!"<<endl;

exit(1);

int mappedIndex=index-lowerBound;

return arr[mappedIndex];

};

OPERATOR OVERLOADING 45
int main()

safearay arr(100,175);

for(int i=100; i<=175; i++)

arr[i]=i*2;

for(int i=100; i<=175; i++)

cout<<"arr["<<i<<"] = "<<arr[i]<<endl;

arr[99]=999;

arr[176]=888;

return 0;

OPERATOR OVERLOADING 46
10. Create a class Polar that represents the points on the plain as polar coordinates
(radius and angle). Create an overloaded +operator for addition of two Polar
quantities. “Adding” two points on the plain can be accomplished by adding their X
coordinates and then adding their Y coordinates.
#include<iostream>

#include<cmath>

using namespace std;

class Polar

private:

double radius;

double angle;

public:

Polar(double r,double a):radius(r),angle(a) {}

Polar operator+(const Polar& other) const

double x1=radius*cos(angle);

double y1=radius*sin(angle);

double x2=other.radius*cos(other.angle);

double y2=other.radius*sin(other.angle);

double x_result=x1+x2;

double y_result=y1+y2;

double radius_result=sqrt(x_result*x_result+y_result*y_result);

double angle_result=atan2(y_result,x_result);

return Polar(radius_result, angle_result);

void display() const

cout<<"Polar Coordinates (Radius, Angle): ("<<radius<<", "<<angle<<"


radians)"<<endl;

};

OPERATOR OVERLOADING 47
int main()

Polar polar1(5.0,M_PI/4);

Polar polar2(3.0,M_PI/3);

cout<<"Polar Point 1: ";

polar1.display();

cout<<"Polar Point 2: ";

polar2.display();

Polar sum=polar1+polar2;

cout<<"Result of Polar Point 1 + Polar Point 2: ";

sum.display();

return 0;

OPERATOR OVERLOADING 48
11. Creates two temporary double variables, one derived from the object of which the
function is a member, and one derived from the argument s2. These double variables
are then added, and the result is converted back to sterling and returned.
#include<iostream>

using namespace std;

class sterling

private:

long pounds;

int shillings;

int pence;

public:

sterling():pounds(0),shillings(0),pence(0) {}

sterling(double decimalPounds);

sterling(long p,int s,int d);

void getSterling();

void putSterling() const;

sterling operator+(const sterling& s2) const;

sterling operator-(const sterling& s2) const;

sterling operator*(double multiplier) const;

sterling operator/(const sterling& s2) const;

sterling operator/(double divisor) const;

operator double() const;

};

sterling::sterling(double decimalPounds)

pounds=static_cast<long>(decimalPounds);

decimalPounds-=pounds;

shillings=static_cast<int>(decimalPounds*20);

decimalPounds-=(shillings/20.0);

pence=static_cast<int>(decimalPounds*240);

OPERATOR OVERLOADING 49
sterling::sterling(long p,int s,int d):pounds(p),shillings(s),pence(d) {}

void sterling::getSterling()

cout<<"Enter the amount in pounds, shillings, and pence (e.g., £9.19.11): £";

char poundSign;

cin>>poundSign>>pounds>>poundSign>>shillings>>poundSign>>pence;

void sterling::putSterling() const

cout<<"£"<<pounds<<"."<<shillings<<"."<<pence;

sterling sterling::operator+(const sterling& s2) const

double totalAmount=static_cast<double>(*this)+static_cast<double>(s2);

return sterling(totalAmount);

sterling sterling::operator-(const sterling& s2) const

double totalAmount=static_cast<double>(*this) - static_cast<double>(s2);

return sterling(totalAmount);

sterling sterling::operator*(double multiplier) const

double totalAmount=static_cast<double>(*this)*multiplier;

return sterling(totalAmount);

sterling sterling::operator/(const sterling& s2) const

double totalAmount=static_cast<double>(*this)/static_cast<double>(s2);

return sterling(totalAmount);

OPERATOR OVERLOADING 50
sterling sterling::operator/(double divisor) const

double totalAmount=static_cast<double>(*this)/divisor;

return sterling(totalAmount);

sterling::operator double() const

double
totalAmount=static_cast<double>(pounds)+(static_cast<double>(shillings)/20.0)+(sta
tic_cast<double>(pence)/240.0);

return totalAmount;

OPERATOR OVERLOADING 51
12. Write a program that incorporates both the bMoney class from Exercise 8 and the
sterling class from Exercise 11. Write conversion operators to convert between
bMoney and sterling, assuming that one pound (£1.0.0) equals fifty dollars ($50.00).
This was the approximate exchange rate in the 19th century when the British Empire
was at its height and the pounds-shillings-pence format was in use. Write a main()
program that allows the user to enter an amount in either currency and th en converts
it to the other currency and displays the result. Minimize any modifications to the
existing bMoney and sterling classes.
#include<iostream>

using namespace std;

class bMoney

private:

long double dollars;

public:

explicit bMoney(long double d):dollars(d) {}

bMoney():dollars(0.0) {}

operator double() const

return dollars/50.0;

void display() const

cout<<"$"<<dollars;

};

class sterling

private:

long pounds;

int shillings;

int pence;

OPERATOR OVERLOADING 52
int main()

char choice;

double amount;

while (true)

cout<<"Choose currency conversion:"<<endl;

cout<<"1. Dollars to Pounds"<<endl;

cout<<"2. Pounds to Dollars"<<endl;

cout<<"3. Exit"<<endl;

cout<<"Enter your choice: ";

cin>>choice;

switch (choice)

case'1':

cout<<"Enter the amount in dollars: $";

cin>>amount;

bMoney b(amount);

double poundsEquivalent=static_cast<double>(b);

cout<<"$"<<amount<<" is equivalent to £"<<poundsEquivalent<<endl;

break;

case'2':

sterling s;

s.getSterling();

double dollarsEquivalent = static_cast<double>(s);

cout<<"£";

s.putSterling();

cout<<" is equivalent to $"<<dollarsEquivalent*50.0<<endl;

break;

OPERATOR OVERLOADING 53
case'3':

cout<<"Exiting the program."<<endl;

return 0;

default:

cout<<"Invalid choice. Please try again."<<endl;

break;

return 0;

OPERATOR OVERLOADING 54

You might also like