Saturday, 2 October 2010

Overloading operator < (lessthan) by using member function



Overloading operator  < (lessthan) by using member function:

If d1,d2 are objects of class ‘Distance’ then
//header files
class Distance
{
Private:
int feet;
float inches;
public:
Distance(int i, float f)
{
feet=i;
inches=f;
}
bool Distance::operator <(Distance); //prototype for overloading the < operator
};

bool Distance :: operator < (Distance d2)
{
if(feet < d2.feet)
return true;
else
return false;
}

void main()
{
Distance d1(4,5), d2(6,7);
if d1< d2;   // < operator is overloaded
cout<<”d1 is lesser than d2”;
if d2< d1;
cout<<”d2 is lesser than d1”;
}

Note: From the above class overloading of <= and >= can be easily learnt.


friend function

No comments:

Post a Comment