Saturday 2 October 2010

Overloading the Pre Increementing operator through a friend function




Overloading the Pre Increementing operator through a friend function
If d1,d2 are objects of class ‘Distance’  then the following statement
d2= ++d1;
is interpretated by the compiler as
d2= operator ++ (Distance);

Example :
class Distance
{
private:
int feet;
float inches;
public:
friend Distance operator ++ (Distance);  // prototype for overloading the pre increment operator
/*
    rest of the class
*/
};

Distance operator ++ (Distance d1 )
{
return distance (++d1.feet, ++d1.inches);
}

void main( )
{
Distance d1,d2;
d2= ++d1;
cout<<d2.feet<< endl <<de.inches;
}


Over loading increement and decreement operators:

operator overloading

friend function 

No comments:

Post a Comment