C++: OOP: Friend Functions

Friend functions are functions defined outside a class (ie, not member functions), but which the class declares to be friends so that they can use the class's private members. This is commonly used in operator overloading.

Overloading input/output operators

Perhaps the most common use of friend functions is overloading << and >> for I/O. See Overloading << and >>.

Commutative operators

Another use of friend functions is to permit operators to be commutative. An operator is commutative if the result is the same regardless of the order of its operands. Some typical examples are addition and multiplication. Subtraction and division are not commutative.

Assuming x is an object of a class you've written and i is an integer, x+i should have the same meaning as i+x. The + in x+i is ok if the + operator between an object and an int is defined as a member function in x's class. However the + in the second case (i+x) can only be written as a friend function. That's because overloading (redefining) operators can only be done for classes, not the primitive types, and the operator definition that is used is based on the class of the left operand.

Declare friends before public and private

A class doesn't control the scope of friend functions so friend function declarations are usually written at the beginning of a .h file. Public and private don't apply to them.

Efficiency

Another possible use of friend functions is efficiency since they can access the private members directly they can avoid the cost of using getter functions. However, never do this unless you really need to because it makes code harder to read and introduces more possible sources of errors thru increased dependencies.

Cosmetic use

Another use is to make some function calls more attractive. For example,
   Time t1, t2;
   . . .
   if (t1.compareTo(t2) == 0) . . .
Might be more attractively written as
   if (compareTo(t1, t2) == 0) . . .
Because compareTo needs to examine the private values in t1 and t2, this second form is only possible if the class declares that compareTo is a friend.