I'm not a friend of the
C++ friends, whether they are functions, member functions or classes. However there are some situations when the use of a friend function can be somehow beneficial, like making the
operator << compatible with a particular class (although it's possible to just override or create a kind of toString() method, like in the best Java flavour).
Lately I've been reading a book on C++ programming. This book is intended to be read by novices, and because of that I think the author should have been more careful when giving advices. This is the way the author justifies friend classes:
"When might you want to make one class a friend to another? Let’s look at an example. Suppose you must program a simple simulation of a television and a remote control. You decide to define a Tv class representing a television and a Remote class representing a remote control. Clearly, there should be some sort of relationship between these classes, but what kind? A remote control is not a television and vice versa, so the is-a relationship of public inheritance doesn’t apply. Nor is either a component of the other, so the has-a relationship of containment or of private or protected inheritance doesn’t apply. What is true is that a remote control can modify the state of a television, and this suggests making the Remote class a friend to the Tv class."
This is exactly the example my teachers at university used to teach as an event broadcast pattern like
Observer, which is by far a better solution.
Friend classes completely break encapsulation, and couples classes so tight that it will be impossible to use one without the other, therefore preventing code reuse.
Labels: c++, programming