You are on page 1of 4

PROGRAM NO.

3A

• AIM

WAP in C++ which overloads + operator to add 2 time object. The class "time"
should contain member variables hour, minute & seconds.

• OBJECTIVE

To study the concept of Operator Overloading.

• THEORY

OPERATOR OVERLOADING

Closely related to function overloading is operator overloading. In C++, you can


overload most operators so that they perform special operations relative to classes that
you create. When an operator is overloaded, none of its original meanings are lost.
Instead, the type of objects it can be applied to is expanded. The ability to overload
operators is one of C++'s most powerful features. It allows the full integration of new
class types into the programming environment. After overloading the appropriate
operators, you can use objects in expressions in just the same way that you use C++'s
built-in data types.

Declaration

A member operator function takes this general form:

ret-type class-name::operator#(arg-list)
{
// operations
}

Often, operator functions return an object of the class they operate on, but ret-type can be
any valid type. The # is a placeholder. When you create an operator function, substitute
the operator for the #. For example, if you are overloading the / operator, use operator/.
When you are overloading a unary operator, arg-list will be empty. When you are
overloading binary operators, arg-list will contain one parameter.
Figure: Overloaded binary operator

• PROGRAM

#include<iostream.h>
#include<conio.h>
class distance
{
private:
int feet;
float inches;
public:
distance()
{
feet=0;
inches=0;
}
distance(int ft, float in)
{
feet=ft;
inches=in;
}
void getdata()
{
cout<<"Enter feet"<<endl;
cin>>feet;
cout<<"Enter inches"<<endl;
cin>>inches;
}
void showdata()
{
cout<<feet<<" "<<inches;
}
distance operator +(distance);
};

distance distance::operator +(distance d2)


{
int f=feet+d2.feet;
float i=inches+d2.inches;
if(i>=12.0)
{
do
{
i=i-12.0;
f++;
}
while(i>=12.0);
}
return distance(f,i);
}
void main()
{
distance d1,d3;
clrscr();
d1.getdata();
distance d2(11, 6.25);
d3=d1+d2;
cout<<"Distance 1:"<<endl;
d1.showdata();
cout<<"\nDistance 2:"<<endl;
d2.showdata();
cout<<"\nDistance 3:"<<endl;
d3.showdata();
getch();
}

• OUTPUT

Enter feet
7
Enter inches
12
Distance D1:
7 12
Distance D2:
11 6.25
Distance D3:
19 6.25
===========================================================
=====

You might also like