Compelling use of Friends?

Hey guys,

This is more of a general question. Have you ever encountered a scenario where friend functions were absolutely necessary or significantly decreased your amount of work?

I'm reading a book right now, and they said that if you wanted to overload the multiplication operator with your own class and a fundamental type, you'd do something like:

1
2
3
4
5
6
7
8
9
class A
{
public:
   ...
private:
   int b;
};
friend A operator*(A &arg, double arg2) { return arg.b * arg2; }
 


So that an external function could access the classes private data members. But if you're truly enforcing encapsulation; you'd have accessor/mutator functions for that class and it wouldn't need direct access.

So, again, my question: Is there a compelling reason to use them?
i've used them in testing but that's about it.
operator* is more commonly implemented in terms of operator*= and does not need to access any private members in any case.

However, it is still useful to define binary operators as friend functions, as long as you do it entirely within the class body, since that hides the operator from non-ADL name lookup, improving encapsulation.
Friends are probably a last resort. They are a logical part of a class though.

Members are not too much fun either:
http://www.gotw.ca/gotw/084.htm
Friends are probably a last resort.

+1.
Friends are probably a last resort.

-1.
Friends are part of a class's encapsulation. They should be used where appropriate.
Last edited on
Topic archived. No new replies allowed.