TITLE: justification for friends (Newsgroups: comp.lang.c++.moderated, 30 Jul 98) ELLSWORTH: scott@eviews.com (Scott Ellsworth) >My rule of thumb is that a friend function, like protected >inheritance, multiple non-interface inheritance, and a few other >features are signs of a potential problem. When they are needed, >they work very, very well, but you should not find yourself needing >the idioms often. CLAMAGE: clamage@Eng.Sun.COM (Steve Clamage) I have to disagree. A friend function should be considered a part of the public interface of the class which for some reason cannot be a member function. If you keep that in mind, it should be clear whether you are misusing friends. Two simple examples: 1. You have a numeric class BigInt, and want to provide an addition operator. If operator+ is a member function, you can write b+5 (where b is a BigInt) but not 5+b. That makes no sense. You want to allow conversion on the left-hand argument, so operator+ cannot be a member function. So either you make it a friend, or you expose enough of the implementation of BigInt that it doesn't need to be a friend. 2. You are implementing a set cooperating classes. Parts of the public interface apply to more than one class. No function can be a member of more than one class, so either you expose the internals of one or more of the classes or you make the function a friend of some of the classes. It is almost always wrong to expose the internals of the implementation, so creating friend functions is the correct design technique in these common examples.