OOPortal OOPortal

Operator Overloading  «Prev 

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.