Monday 6 April 2015

Operator Overloading Using Friend Functions

Friend functions play a very important role in operator overloading by providing the flexibility denied by the member functions of a class. They allow overloading of stream operators for stream computation on user defined data types.

The only difference between a friend function and member function is that, the friend function requires the arguments to be explicitly passed to the function and processes them explicitly, whereas the member function considers the first argument implicitly.

Friend functions can either be used with unary or binary operators. The syntax of operator overloading with friend functions is

Friend return_type operator Operator_Symbol (arg1, arg2,…..)
{
// body of function
}

Difference between the normal function and friend function

? The prototype of friend function must be prefixed with the keyword friend inside the class body.

? The body of friend function can appear either inside or outside the body of a class. It is advisable to define    a friend function outside the body of a class.

? The definition of the friend function outside the body of a class is defined as normal function and is not             prefixed with the friend keyword.
? The arguments of the friend functions are generally objects of friend classes. In a friend function, using its        objects can access all the members of a class.
? Friend function is not allowed to access members of a class directly, but it can access all the members            including the private members by using objects of that class.
? Friend function is similar to the normal member function except that it can access the private members of a   class using its objects.


No comments:

Post a Comment