Can you explain to me why the friend keyword is preferred for giving access rights to private data of class?
1 Answer
Friend is the classic way of extending the interface of a class.
But the great thing is that friend explicitly documents your intention to tightly bind specific items to a class.
Note: By using friend you are tightly binding the friends to the class.
A perfect example is the stream operators in C++
class Plop { private: int value; friend std::ostream& operator<<(std::ostream& stream, Plop const& data); friend std::istream& operator>>(std::istream& stream, Plop& data); }; std::ostream& operator<<(std::ostream& stream, Plop const& data) { return stream << data.value << " "; } std::istream& operator>>(std::istream& stream, Plop& data) { return stream >> data.value; } 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.
- If you could publicly access the data (e.g. via a getter) would you have used a free function instead?Ioanna– Ioanna2016-12-21 09:41:29 +00:00Commented Dec 21, 2016 at 9:41
friendwas preferred, what other ways do you usually use to access private class data from the outside?