Assignment 02
Assignment 02
class Counter
private:
public:
Counter():count(0)
{ }
{ 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>
class Counter
private:
public:
Counter():count(0)
{ }
{ 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>
class Counter
private:
public:
Counter():count(0)
{ }
Counter(int c):count(c)
{ }
{ 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>
class Counter
private:
public:
Counter():count(0)
{ }
Counter(int c):count(c)
{ }
{ return count; }
Counter operator ++ ()
return Counter(++count);
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>
class Distance
private:
int feet;
float inches;
public:
Distance():feet(0),inches(0.0)
{ }
{ }
void getdist()
{ cout<<feet<<"\’-"<<inches<<"\”"; }
};
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;
return 0;
OPERATOR OVERLOADING 7
6. Overloaded ‘+’ operator concatenates strings:
#include<iostream>
#include<string.h>
#include<stdlib.h>
class String
private:
enum { SZ=80 };
char str[SZ];
public:
String()
{ strcpy(str, “”); }
{ strcpy(str, s); }
{ cout<<str; }
String temp;
if( strlen(str)+strlen(ss.str)<SZ )
strcpy(temp.str,str);
strcat(temp.str,ss.str);
else
return temp;
};
OPERATOR OVERLOADING 8
int main()
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>
class Distance
private:
int feet;
float inches;
public:
Distance():feet(0),inches(0.0)
{ }
{ }
void getdist()
{ cout<<feet<<"\’-"<<inches<<"\”"; }
};
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);
if( dist1<dist2 )
else
cout<<endl;
return 0;
OPERATOR OVERLOADING 11
8. Overloaded ‘==’ operator compares strings:
#include<iostream>
#include<string.h>
class String
private:
enum { SZ=80 };
char str[SZ];
public:
String()
{ strcpy(str,“”); }
{ strcpy(str,s); }
{ cout<<str; }
void getstr()
{ cin.get(str,SZ); }
};
OPERATOR OVERLOADING 12
int main()
String s1="yes";
String s2="no";
String s3;
s3.getstr();
if(s3==s1)
elseif(s3==s2)
else
return 0;
OPERATOR OVERLOADING 13
9. Overloaded ‘+=’ assignment operator:
#include<iostream>
class Distance
private:
int feet;
float inches;
public:
Distance():feet(0),inches(0.0)
{ }
{ }
void getdist()
{ cout<<feet<<"\’-"<<inches<<"\”"; }
};
feet+=d2.feet;
inches+=d2.inches;
if(inches>=12.0)
inches-=12.0;
feet++;
OPERATOR OVERLOADING 14
int main()
Distance dist1;
dist1.getdist();
Distance dist2(11,6.25);
dist1+=dist2;
cout<<"\nAfter addition,";
cout<<endl;
return 0;
OPERATOR OVERLOADING 15
10. Creates safe array, uses separate put and get functions:
#include<iostream>
#include<process.h>
class safearay
private:
int arr[LIMIT];
public:
if(n<0||n>=LIMIT)
arr[n]=elvalue;
if(n<0||n>=LIMIT)
return arr[n];
};
OPERATOR OVERLOADING 16
int main()
safearay sa1;
sa1.putel(j, j*10);
int temp=sa1.getel(j);
return 0;
OPERATOR OVERLOADING 17
11. Uses one access() function for both put and get:
#include<iostream>
#include<process.h>
class safearay
private:
int arr[LIMIT];
public:
int& access(int n)
if(n<0||n>=LIMIT )
return arr[n];
};
int main()
safearay sa1;
sa1.access(j)=j*10;
int temp=sa1.access(j);
return 0;
OPERATOR OVERLOADING 18
12. Uses overloaded [] operator for both put and get:
#include<iostream>
#include<process.h>
class safearay
private:
int arr[LIMIT];
public:
if(n<0||n>=LIMIT)
return arr[n];
};
int main()
safearay sa1;
int temp=sa1[j];
return 0;
OPERATOR OVERLOADING 19
13. Distance to meters, meters to Distance:
#include<iostream>
class Distance
private:
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);
inches(in),MTF(3.280833F)
{ }
void getdist()
{ cout<<feet<<"\’-"<<inches<<"\”"; }
float fracfeet=inches/12;
fracfeet+=static_cast<float>(feet);
return fracfeet/MTF;
OPERATOR OVERLOADING 20
};
int main()
float mtrs;
Distance dist1=2.35F;
mtrs=static_cast<float>(dist1);
Distance dist2(5,10.25);
mtrs=dist2;
return 0;
OPERATOR OVERLOADING 21
14. Convert between ordinary strings and class String :
#include<iostream>
#include<string.h>
class String
private:
enum { SZ=80 };
char str[SZ];
public:
String()
{ str[0]=‘\0’; }
{ strcpy(str, s); }
operator char*()
{ return str; }
};
int main()
String s1;
s1 = xstr;
s1.display();
cout<<static_cast<char*>(s2);
cout<<endl;
return 0;
OPERATOR OVERLOADING 22
15. Creates a class name ‘scrollbar’:
#include<iostream>
#include<string>
class scrollbar
private:
int size;
public:
{ }
{ size = sz; }
{ owner = own; }
{ return size; }
{ return owner; }
};
int main()
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>
class Distance
private:
int feet:
float inches;
public:
Distance();
int new_feet=feet+other.feet;
int new_inches=inches+other.inches;
if(new_inches>=12)
new_feet+=1;
new_inches-=12;
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;
};
Distance::Distance():feet(0),inches(0) {}
int main()
Distance dist1(5,6);
Distance dist2(3,8);
Distance dist3=dist1+dist2;
dist3.display();
Distance dist4=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>
class MyString
private:
char* str;
public:
MyString(const char* s)
str=new char[strlen(s)+1];
strcpy(str,s);
strcpy(temp,str);
strcat(temp,other.str);
delete[] str;
str=temp;
return*this;
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>
class Time
private:
int hours;
int minutes;
public:
Time():hours(0),minutes(0) {}
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;
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>
class Int
private:
public:
checkOverflow(result);
return Int(result);
checkOverflow(result);
return Int(result);
checkOverflow(result);
return Int(result);
OPERATOR OVERLOADING 30
{
if(other.value==0)
exit(1);
checkOverflow(result);
return Int(result);
cout<<value;
private:
if(result>numeric_limits<int>::max()||result<numeric_li mits<int>::min())
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>
class Time
private:
int hours;
int minutes;
public:
Time():hours(0),minutes(0) {}
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);
time.display();
cout<<endl;
++time;
time.display();
cout<<endl;
Time temp1=time++;
time.display();
cout<<endl;
temp1.display();
cout<<endl;
--time;
time.display();
cout<<endl;
Time temp2=time--;
time.display();
cout<<endl;
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>
class Time
private:
int hours;
int minutes;
public:
Time():hours(0),minutes(0) {}
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;
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;
difference.display();
cout<<endl;
Time product=time1*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>
class Fraction
private:
int numerator;
int denominator;
if(b==0)
return a;
return gcd(b,a%b);
void reduce()
int common=gcd(numerator,denominator);
numerator/=common;
denominator/=common;
public:
if(denominator==0)
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);
int newNumerator=(numerator*other.denominator)-
(other.numerator*denominator);
int newDenominator=denominator*other.denominator;
return Fraction(newNumerator,newDenominator);
int newNumerator=numerator*other.numerator;
int newDenominator=denominator*other.denominator;
return Fraction(newNumerator,newDenominator);
if(other.numerator==0)
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);
return !(*this==other);
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;
sum.display();
cout<<endl;
Fraction diff=frac1-frac2;
OPERATOR OVERLOADING 40
diff.display();
cout<<endl;
Fraction product=frac1*frac2;
product.display();
cout<<endl;
Fraction quotient=frac1/frac2;
quotient.display();
cout<<endl;
if(frac1==frac2)
else
if(frac1!=frac2)
else
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>
class bMoney
private:
istringstream iss(str);
iss>>result;
return result;
public:
bMoney():money(0.0) {}
return bMoney(money+other.money);
return bMoney(money-other.money);
return bMoney(money*value);
OPERATOR OVERLOADING 42
long double operator/(const bMoney& other) const
if (other.money==0.0)
exit(1);
return money/other.money;
if(value==0.0)
exit(1);
return bMoney(money/value);
cout<<"$"<<money;
};
int main()
string input1,input2;
while (true)
OPERATOR OVERLOADING 43
cout<<"Enter the first money amount (e.g., $12345.67): ";
cin>>input1;
if(input1=="0/1"||input1=="0/1")
break;
cin>>input2;
cin>>pricePerWidget;
bMoney money1(input1);
bMoney money2(input2);
bMoney sum=money1+money2;
bMoney difference=money1-money2;
bMoney product=money1*pricePerWidget;
bMoney division2=money1/pricePerWidget;
cout<<"Sum: ";
sum.display();
cout<<"Difference: ";
difference.display();
cout<<endl;
cout<<"Product: ";
product.display();
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>
class safearay
private:
int arr[LIMIT];
int lowerBound;
int upperBound;
public:
if(lowerBound>upperBound)
exit(1);
if(index<lowerBound||index>upperBound)
exit(1);
int mappedIndex=index-lowerBound;
return arr[mappedIndex];
};
OPERATOR OVERLOADING 45
int main()
safearay arr(100,175);
arr[i]=i*2;
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>
class Polar
private:
double radius;
double angle;
public:
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);
};
OPERATOR OVERLOADING 47
int main()
Polar polar1(5.0,M_PI/4);
Polar polar2(3.0,M_PI/3);
polar1.display();
polar2.display();
Polar sum=polar1+polar2;
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>
class sterling
private:
long pounds;
int shillings;
int pence;
public:
sterling():pounds(0),shillings(0),pence(0) {}
sterling(double decimalPounds);
void getSterling();
};
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;
cout<<"£"<<pounds<<"."<<shillings<<"."<<pence;
double totalAmount=static_cast<double>(*this)+static_cast<double>(s2);
return sterling(totalAmount);
return sterling(totalAmount);
double totalAmount=static_cast<double>(*this)*multiplier;
return sterling(totalAmount);
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);
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>
class bMoney
private:
public:
bMoney():dollars(0.0) {}
return dollars/50.0;
cout<<"$"<<dollars;
};
class sterling
private:
long pounds;
int shillings;
int pence;
OPERATOR OVERLOADING 52
int main()
char choice;
double amount;
while (true)
cout<<"3. Exit"<<endl;
cin>>choice;
switch (choice)
case'1':
cin>>amount;
bMoney b(amount);
double poundsEquivalent=static_cast<double>(b);
break;
case'2':
sterling s;
s.getSterling();
cout<<"£";
s.putSterling();
break;
OPERATOR OVERLOADING 53
case'3':
return 0;
default:
break;
return 0;
OPERATOR OVERLOADING 54