Page 154 - DCAP404 _Object Oriented Programming
P. 154
Unit 7: Operator Overloading
integer objsum; Notes
objsum = obj1 + obj2;
obj1.disp();
obj2.disp();
objsum.disp();
getch();
}
You should see the following output.
value = 11
value = 22
value = 33
Friend function being a non-member function does not belong to any class. This function is
invoked like a normal function. Hence the two objects that are to be added have to be passed as
arguments exclusively.
Task Analyze the uses of friend function in operator overloading.
7.4.2 Using Member Function
In the unit on overloading the arithmetic operators, you learned that when the operator does
not modify it’s operands, it’s best to implement the overloaded operator as a friend function of
the class. For operators that do modify their operands, we typically overload the operator using
a member function of the class.
Overloading operators using a member function is very similar to overloading operators using
a friend function. When overloading an operator using a member function:
1. The leftmost operand of the overloaded operator must be an object of the class type.
2. The leftmost operand becomes the implicit *this parameter. All other operands become
function parameters.
Most operators can actually be overloaded either way, however there are a few exception cases:
3. If the leftmost operand is not a member of the class type, such as when overloading
operator+(int, YourClass), or operator<<(ostream&, YourClass), the operator must be
overloaded as a friend.
4. The assignment (=), subscript ([]), call (()), and member selection (->) operators must be
overloaded as member functions.
Overloading the unary negative (–) operator
The negative operator is a unary operator that can be implemented using either method. Before
we show you how to overload the operator using a member function, here’s a reminder of how
we overloaded it using a friend function:
class Cents
LOVELY PROFESSIONAL UNIVERSITY 147