Download

Do friends violate encapsulation?

For example, you can use them to split code into two classes and have their data inaccessible for code in all other classes. Or you can use them as "a syntactic variant" of member functions.

Think of the friends as part of the class interface instead of something outside the class.

FQA: What encapsulation? C++ doesn't have encapsulation. It has access control (code outside of a class using private members of this class will not compile), but it has neither compile time encapsulation (stable binary interfaces) nor run time encapsulation (safe memory access). What's there to violate?

The case of two classes was discussed in the previous FAQ; this argument only sounds convincing if you think C++ classes are a good way to define the important, stable interfaces in your system.

As to the "syntactic variant" business, it's probably about overloaded operators. The C++ syntax makes it impossible to define overloaded operators as class members unless the first argument is an object of the class. Since C++ uses stream<<obj to print things, many classes declare a friend operator<<, for example. This argument is only interesting if you think C++ operator overloading is any good.