TITLE: what are friends for PROBLEM: beamsley@mail.ic.net (Bob Kundrat) Would anyone with an opinion concerning the use of friend functions in a class implementation please comment on whether or not they feel strongly against there usage totally or whether they feel they should be used where appropriate. RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 27 Nov 95 Some people claim that friend functions violate encapsulation. I claim that is a red herring. You can certainly use friendship to violate encapsulation, but you can also use the "public:" access modifier to violate encapsulation. Does that mean a class should have no public members? IMHO, the proper way to view a friend function is that it is part of the public interface of the class. From a design viewpoint, it is not significantly different from a public static member function -- it has access to all parts of a class, but doesn't have a "this" pointer. Two situations where you prefer a friend function to a member function: - an overloaded operator (like "+" for class complex) where you do want to allow type conversion on the left-hand operand. - a design is best expressed as two or more cooperating classes (such as a container and its iterator) and a member of one class requires access to implementation details of the other. To me, "breaking encapsulation" means that you allow design details to escape in an uncontrolled fashion. For example, making any member public means that you cannot change the declaration of that member, since you cannot know what outside code might depend on that declaration. A friend function must be declared in the class itself; you have a complete list of functions which may depend on private class data. The friend functions should be thought of as part of the class implementation.