Coupon Accepted Successfully!


Overloading with friend Function

The friend functions are more useful in operator overloading. They offer better flexibility, which is not provided by the member function of the class. The difference between member function and friend function is that the member function takes argument explicitly. On the contrary, the friend function needs the parameters to be explicitly passed. The syntax of operator overloading with friend function is as follows:

The keyword friend precedes function prototype declaration. It must be written inside the class. The function can be defined inside or outside the class. The arguments used in friend function are generally objects of the friend classes. A friend function is similar to normal function; the only difference being that friend function can access private member of the class through the objects. friend function has no permission to access private members of a class directly. However, it can access the private members through objects of the same class.

10.9 Write a program to overload unary operator using friend function.


Explanation: In the above program, operator – is overloaded using friend function. The operator function is defined as friend. The statement c2=−c1 invokes the operator function. This statement also returns the negated values of c1 without affecting actual value of c1 and assigns it to object c2.

The negation operation can also be used with an object to alter its own data member variables. In such a case, the object itself acts as a source and destination object. This can be accomplished by sending reference of object. The following program illustrates this.

10.10 Write a program to pass reference of an object to operator function.


Explanation: In the above program, the object c1 itself acts as a source and destination object. The reference of object is passed to operator function. The object c is a reference object of c1. The values of object c are replaced by itself by applying negation.

Test Your Skills Now!
Take a Quiz now
Reviewer Name