Can you explain to me why the friend keyword is preferred for giving access rights to private data of class?

  • 1
    If you ask for why friend was preferred, what other ways do you usually use to access private class data from the outside? Commented Aug 9, 2011 at 4:26
  • @honk "Preferred" might be the wrong word to use here. I edited most of the post to correct grammar and whatnot and I kept the original word choice, but I think there may be a language barrier here.
    – Adam Lear
    Commented Aug 9, 2011 at 4:44
  • I don't know because I read about friend today by chance. and the article says if I don't use friend, I will create a monolit class.
    – Dalton
    Commented Aug 9, 2011 at 4:49

1 Answer 1


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
        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
    Commented Dec 21, 2016 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.