TITLE: hate friends/love friends (Newsgroups: comp.lang.c++.moderated, 28 July 2000) UZDAVINIS: Chris Uzdavinis > Friends are terrible because they expose everything, but they're great > when you want individually grant access to the private interface of > your class. CLAMAGE: Steve Clamage Do you have similar love-hate feelings about hammers or scissors? Friendship in C++ is a low-level implementation tool, and like hammers and scissors, can be used appropriately, or misused. Take a step back: You want to define an interface to a facility. Perhaps the facility is best designed and implemented as a single class, or perhaps it is best done as two or more cooperating classes. (A container and its iterators are examples of the latter.) Now we come to the functional interface. Part of the interface will probably be member functions. But often, part of the functional interface cannot or ought not be implemented as member functions. A numeric class will want arithmetic operators. If you make them members, you get assymetry, because you can't get type conversion on the left-hand operand. Then you wind up with m + 1 // ok 1 + m // error So operator+ should not be a member function, but for efficiency should have access to implementation details. Either you make those implementation details to some degree part of the public interface, or you make operator+ a friend. In the case of cooperating classes, a function cannot be a member of two classes, and if it needs access to implementation details of both classes, you have the same problem: expose some part of the implementation details, or make the function a friend of the other class. If you view friend functions as part of the public interface of a class, instead of as violators of encapsualtion, the problem vanishes. In addition, a friend function must be declared inside the class, so it even LOOKS like part of the public interface! _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com