Friend functions exist in order to present free functions as a contiguous part of the class interface. There are a few places where free functions are part of a class interface. Example: Suppose you have an arbitrary-precision class BigNum
. Here are some obvious candidates for friend functions:
// binary operators where BigNum isn't the left-hand operand
BigNum operator+ (int, BigNum);
BigNum operator- (int, BigNum);
// stream operators
std::ostream &operator<< (std::ostream &os, const BigNum &num);
std::istream &operator>> (std::istream &is, BigNum &num);
Now, given those two examples, in many cases the binary operators don't need to be friends (e.g. I can implement int + BigNum
by delegating to BigNum + int
, which is a member function and thus already has full access). But it all depends on what your needs are for performance, and what you are willing to expose through the class's public member functions.