Program No. 3A AIM: Ret-Type Class-Name::operator# (Arg-List) (// Operations)
Program No. 3A AIM: Ret-Type Class-Name::operator# (Arg-List) (// Operations)
Program No. 3A AIM: Ret-Type Class-Name::operator# (Arg-List) (// Operations)
3A
• AIM
WAP in C++ which overloads + operator to add 2 time object. The class "time"
should contain member variables hour, minute & seconds.
• OBJECTIVE
• THEORY
OPERATOR OVERLOADING
Declaration
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);
};
• OUTPUT
Enter feet
7
Enter inches
12
Distance D1:
7 12
Distance D2:
11 6.25
Distance D3:
19 6.25
===========================================================
=====