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

Symmetrical Binary Operators
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