“… much as in real life, friends are often more trouble than they are worth.”
Scott Meyers
Effective C++
Friend classes in C++ are one of the oddest constructs. Despite their existence in the language, pretty much every discussion you encounter on the topic says it is best to avoid them. In fact, as other object-oriented languages have demonstrated, you don’t need them. Consider SmallTalk whose purist approach to object-orientation prevents objects of the same type from accessing each other’s private data. This, however, can result in rather awkward interfaces. As a simple example, if this were the case in C++, the following class could not be implemented as it is defined
class Audio {
private:
AudioStream audioStream;
public:
Audio(String audioFilePath);
void moveTo(double timeInSeconds);
void splice(Audio &source, double atTimeInSeconds) {
moveTo(atTimeInSeconds);
audioStream.insert(source.audioStream);
}
}
The problem would be that the operation splice() attempts to access the private attribute audioStream of the incoming source object. To solve this, the Audio class would need to define an
accessor to access the raw audio stream. This is probably not the intention of the designer since it doesn’t make sense to publicly make available such information.
For the most part, when explaining object-oriented programming, we make a big fuss about information hiding and designing for objects that expose only the bare essentials to the world, zealously protecting their personal memory. We try to use every conceivable metaphor and picture to illustrate the concept. Friends completely circumvent these ideas.
(more…)