Can you explain to me why the
friend keyword is preferred for giving access rights to private data of class?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
Friend is the classic way of extending the interface of a class.
Note: By using friend you are tightly binding the friends to the class.
A perfect example is the stream operators in C++
Here we are extending the public interface of the Plop class in a way that allows us to stream the object into and out of a stream, but without exposing the internal implementation or causing future implementation headaches by requiring the use of get/set methods that must be maintained (because they would be part of the public interface) even if the internal implementation is changed.
Note: This does NOT break encapsulation but it does tightly bind the stream operators to the implementation of the Plop class (ie any change to the implementation of the Plop class will require a change to the implementation of the stream operators). But this is expected. All parts of the public interface (including public/protected methods) are tightly bound to the implementation.
But Note: You have explicitly documented this binding as part of the class declaration.
Note: I would not refer to friend as the preferred way to expose private data. Over-use of friend can be just as bad as exposing the implementation. Like all language features it should be used judiciously.