Operator Overloading  «Prev  Next»
Lesson 9 Overloading binary operators
Objective Write member functions to overload binary operators

Overloading Binary Operators

We continue with our clock example and show how to overload binary operators. Basically, the same principles hold.
When a binary operator is overloaded using a member function, it has
  1. the implicitly passed object as its first argument
  2. the lone argument list parameter as its second argument

Overloading Binary Operators

Generally speaking, you should overload symmetrical binary operators, such as
  1. +,
  2. *,
  3. ==,
  4. !=,

or && with friend functions. Both arguments are then passed as ordinary parameters. This subjects both arguments to the same rules of parameter passing. Recall that using a member function to provide overloading for symmetrical binary operators causes the first argument to be passed via the this pointer.

Declarations for Friends

A friend declaration only specifies access. It is not a general declaration of the function. If we want users of the class to be able to call a friend function, then we must also declare the function separately from the friend declaration. To make a friend visible to users of the class, we usually declare each friend (outside the class) in the same header as the class itself. Thus, our Sales_data header should provide separate declarations (aside from the friend declarations inside the class body) for read, print, and add.
Many compilers do not enforce the rule that friend functions must be declared outside the class before they can be used.
Some compilers allow calls to a friend function when there is no ordinary declaration for that function. Even if your compiler allows such calls, it is a good idea to provide separate declarations for friends. That way you will not have to change your code if you use a compiler that enforces this rule.
When a binary operator is overloaded using a friend or nonmember function, both arguments are specified in the parameter list.
Remember, though, that nonmember functions that are not friend functions cannot access private members of a class.
Create an operation for clock that will add two values together.

class clock {
 .....
 friend clock  operator+(clock c1, clock c2);
};

clock operator+(clock c1, clock c2){
 return (c1.tot_secs + c2.tot_secs);
}

The integer expression is implicitly converted to a clock by the conversion constructor clock::clock(unsigned long). Both clock values are passed as function arguments, and both are candidates for assignment conversions. Because operator+() is a symmetrical binary operator, the arguments should be treated identically. Thus, it is normal for symmetrical binary operators to be overloaded by friend functions.

Overloading Binary Operators - Exercise

Click the Exercise link below to try your hand at overloading several arithmetic binary operators in a class that implements a set.
Overloading Binary Operators - Exercise