<p>I have been reading through the <a href="http://yosefk.com/c++fqa/" rel="noreferrer">C++ FAQ</a> and was curious about the <a href="http://yosefk.com/c++fqa/friend.html" rel="noreferrer"><code>friend</code></a> declaration. I personally have never used it, however I am interested in exploring the language. </p>

<p>What is a good example of using <code>friend</code>?</p>

<hr>

<p>Reading the FAQ a bit longer I like the idea of the <code>&lt;&lt;</code> <code>&gt;&gt;</code> operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?</p>

[{'answer_id': 17436, 'author': 'Ryan Fox', 'author_id': 55, 'author_profile': 'https://Stackoverflow.com/users/55', 'pm_score': 0, 'selected': False, 'text': "<p>When implementing tree algorithms for class, the framework code the prof gave us had the tree class as a friend of the node class.</p>\n\n<p>It doesn't really do any good, other than let you access a member variable without using a setting function.</p>\n"}, {'answer_id': 17443, 'author': 'Andrew Grant', 'author_id': 1043, 'author_profile': 'https://Stackoverflow.com/users/1043', 'pm_score': 9, 'selected': True, 'text': "<p>Firstly (IMO) don't listen to people who say <code>friend</code> is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas. </p>\n\n<p>There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions).</p>\n\n<p>Onto the answer; </p>\n\n<p>The <code>friend</code> specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name. </p>\n\n<p>You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.</p>\n\n<pre><code>class Child\n{\n//Mother class members can access the private parts of class Child.\nfriend class Mother;\n\npublic:\n\n  string name( void );\n\nprotected:\n\n  void setName( string newName );\n};\n</code></pre>\n"}, {'answer_id': 17444, 'author': 'fulmicoton', 'author_id': 446497, 'author_profile': 'https://Stackoverflow.com/users/446497', 'pm_score': 1, 'selected': False, 'text': '<p>The tree example is a pretty good example : \nHaving an object implemented in a few different class without\nhaving an inheritance relationship.</p>\n\n<p>Maybe you could also need it to have a constructor protected and force\npeople to use your "friend" factory.</p>\n\n<p>... Ok, Well frankly you can live without it.</p>\n'}, {'answer_id': 17451, 'author': 'csmba', 'author_id': 350, 'author_profile': 'https://Stackoverflow.com/users/350', 'pm_score': 3, 'selected': False, 'text': '<p>You control the access rights for members and functions using Private/Protected/Public right?\nso assuming the idea of each and every one of those 3 levels is clear, then it should be clear that we are missing something... </p>\n\n<p>The declaration of a member/function as protected for example is pretty generic. You are saying that this function is out of reach for <strong>everyone</strong> (except for an inherited child of course). But what about exceptions? every security system lets you have some type of \'white list" right?</p>\n\n<p>So <em>friend</em> lets you have the flexibility of having rock solid object isolation, but allows for a "loophole" to be created for things that you feel are justified.</p>\n\n<p>I guess people say it is not needed because there is always a design that will do without it. I think it is similar to the discussion of global variables: You should never use them, There is always a way to do without them... but in reality, you see cases where that ends up being the (almost) most elegant way... I think this is the same case with friends.</p>\n\n<blockquote>\n  <p>It doesn\'t really do any good, other than let you access a member variable without using a setting function</p>\n</blockquote>\n\n<p>well that is not exactly the way to look at it.\nThe idea is to control WHO can access what, having or not a <em>setting function</em> has little to do with it. </p>\n'}, {'answer_id': 17499, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 5, 'selected': False, 'text': "<p>The canonical example is to overload operator&lt;&lt;.  Another common use is to allow a helper or admin class access to your internals.</p>\n\n<p>Here are a couple of guidelines I heard about C++ friends.  The last one is particularly memorable.</p>\n\n<ul>\n<li>Your friends are not your child's friends.</li>\n<li>Your child's friends are not your friends.</li>\n<li>Only friends can touch your private parts.</li>\n</ul>\n"}, {'answer_id': 17505, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 6, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c#17460">@roo</a>: Encapsulation is not broken here because the class itself dictates who can access its private members. Encapsulation would only be broken if this could be caused from outside the class, e.g. if your <code>operator &lt;&lt;</code> would proclaim “I\'m a friend of class <code>foo</code>.”</p>\n\n<p><code>friend</code> replaces use of <code>public</code>, not use of <code>private</code>!</p>\n\n<p>Actually, the C++ FAQ <a href="https://isocpp.org/wiki/faq/friends#friends-and-encap" rel="noreferrer">answers this already</a>.</p>\n'}, {'answer_id': 17529, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 0, 'selected': False, 'text': "<p>You <strong>could</strong> adhere to the strictest and purest OOP principles and ensure that no data members for any class even have <em>accessors</em> so that all objects <strong>must</strong> be the only ones that can know about their data with the only way to act on them is through indirect <em>messages</em>, i.e., methods.</p>\n\n<p>But even C# has an <strong>internal</strong> visibility keyword and Java has its default <strong>package</strong> level accessibility for some things. C++ comes actually closer to the OOP ideal by minimizinbg the compromise of visibility into a class by specifying <strong><em>exactly</em></strong> which other class and <strong>only</strong> other classes could see into it. </p>\n\n<p>I don't really use C++ but if C# had <em>friend</em>s I would that instead of the assembly-global <strong>internal</strong> modifier, which I actually use a lot. It doesn't really break incapsulation, because the unit of deployment in .NET <strong>is</strong> an assembly.</p>\n\n<p>But then there's the <strong>InternalsVisibleTo</strong>Attribute(otherAssembly) which acts like a cross-assembly <strong>friend</strong> mechanism. Microsoft uses this for visual <em>designer</em> assemblies.</p>\n"}, {'answer_id': 17597, 'author': 'popopome', 'author_id': 1556, 'author_profile': 'https://Stackoverflow.com/users/1556', 'pm_score': 2, 'selected': False, 'text': '<p>To do TDD many times I\'ve used \'friend\' keyword in C++.</p>\n\n<p>Can a friend know everything about me?</p>\n\n<hr>\n\n<p>Updated: I found this valuable answer about "friend" keyword from <a href="http://www.research.att.com/~bs/bs_faq2.html" rel="nofollow noreferrer">Bjarne Stroustrup site</a>.</p>\n\n<blockquote>\n  <p>"Friend" is an explicit mechanism for granting access, just like membership.</p>\n</blockquote>\n'}, {'answer_id': 17646, 'author': 'roo', 'author_id': 716, 'author_profile': 'https://Stackoverflow.com/users/716', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n  <p>To do TDD many times I've used 'friend' keyword in C++.<br />Can a friend know everything about me?</p>\n</blockquote>\n\n<p>No, its only a one way friendship :`(</p>\n"}, {'answer_id': 17970, 'author': 'Matt Dillard', 'author_id': 863, 'author_profile': 'https://Stackoverflow.com/users/863', 'pm_score': 1, 'selected': False, 'text': '<p>One specific instance where I use <code>friend</code> is when creating <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">Singleton</a> classes.  The <code>friend</code> keyword lets me create an accessor function, which is more concise than always having a "GetInstance()" method on the class.</p>\n\n<pre><code>/////////////////////////\n// Header file\nclass MySingleton\n{\nprivate:\n    // Private c-tor for Singleton pattern\n    MySingleton() {}\n\n    friend MySingleton&amp; GetMySingleton();\n}\n\n// Accessor function - less verbose than having a "GetInstance()"\n//   static function on the class\nMySingleton&amp; GetMySingleton();\n\n\n/////////////////////////\n// Implementation file\nMySingleton&amp; GetMySingleton()\n{\n    static MySingleton theInstance;\n    return theInstance;\n}\n</code></pre>\n'}, {'answer_id': 19793, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>With regards to operator&lt;&lt; and  operator>> there is no good reason to make these operators friends.  It is true that they should not be member functions, but they don't need to be friends, either.</p>\n\n<p>The best thing to do is create public print(ostream&amp;) and read(istream&amp;) functions.  Then, write the operator&lt;&lt; and operator>> in terms of those functions.  This gives the added benefit of allowing you to make those functions virtual, which provides virtual serialization.</p>\n"}, {'answer_id': 25916, 'author': 'rptony', 'author_id': 1781, 'author_profile': 'https://Stackoverflow.com/users/1781', 'pm_score': 3, 'selected': False, 'text': '<p>Friend comes handy when you are building a container and you want to implement an iterator for that class.  </p>\n'}, {'answer_id': 35846, 'author': 'Dominik Grabiec', 'author_id': 3719, 'author_profile': 'https://Stackoverflow.com/users/3719', 'pm_score': 7, 'selected': False, 'text': "<p>At work we <strong>use friends for testing code</strong>, extensively. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have separate test code that uses friends to inspect internal state and data for testing.</p>\n\n<p>Suffice to say I wouldn't use the friend keyword as an essential component of your design.</p>\n"}, {'answer_id': 44985, 'author': 'Ray', 'author_id': 456786, 'author_profile': 'https://Stackoverflow.com/users/456786', 'pm_score': 2, 'selected': False, 'text': '<p>We had an interesting issue come up at a company I previously worked at where we used friend to decent affect.  I worked in our framework department we created a basic engine level system over our custom OS.  Internally we had a class structure:</p>\n\n<pre><code>         Game\n        /    \\\n TwoPlayer  SinglePlayer\n</code></pre>\n\n<p>All of these classes were part of the framework and maintained by our team.  The games produced by the company were built on top of this framework deriving from one of Games children.  The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes.  The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship.  </p>\n\n<p>Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had.  </p>\n'}, {'answer_id': 53345, 'author': 'maccullt', 'author_id': 4945, 'author_profile': 'https://Stackoverflow.com/users/4945', 'pm_score': 3, 'selected': False, 'text': "<p>Another common version of Andrew's example, the dreaded code-couplet</p>\n\n<pre><code>parent.addChild(child);\nchild.setParent(parent);\n</code></pre>\n\n<p>Instead of worrying if both lines are always done together and in consistent order you could make the methods private and have a friend function to enforce consistency:</p>\n\n<pre><code>class Parent;\n\nclass Object {\nprivate:\n    void setParent(Parent&amp;);\n\n    friend void addChild(Parent&amp; parent, Object&amp; child);\n};\n\nclass Parent : public Object {\nprivate:\n     void addChild(Object&amp; child);\n\n     friend void addChild(Parent&amp; parent, Object&amp; child);\n};\n\nvoid addChild(Parent&amp; parent, Object&amp; child) {\n    if( &amp;parent == &amp;child ){ \n        wetPants(); \n    }\n    parent.addChild(child);\n    child.setParent(parent);\n}\n</code></pre>\n\n<p>In other words you can keep the public interfaces smaller and enforce invariants that cut across classes and objects in friend functions.</p>\n"}, {'answer_id': 362581, 'author': 'shash', 'author_id': 11684, 'author_profile': 'https://Stackoverflow.com/users/11684', 'pm_score': -1, 'selected': False, 'text': "<p>Friends are also useful for callbacks. You could implement callbacks as static methods</p>\n\n<pre><code>class MyFoo\n{\nprivate:\n    static void callback(void * data, void * clientData);\n    void localCallback();\n    ...\n};\n</code></pre>\n\n<p>where <code>callback</code> calls <code>localCallback</code> internally, and the <code>clientData</code> has your instance in it. In my opinion, </p>\n\n<p>or...</p>\n\n<pre><code>class MyFoo\n{\n    friend void callback(void * data, void * callData);\n    void localCallback();\n}\n</code></pre>\n\n<p>What this allows is for the friend to be a defined purely in the cpp as a c-style function, and not clutter up the class.</p>\n\n<p>Similarly, a pattern I've seen very often is to put all the <em>really</em> private members of a class into another class, which is declared in the header, defined in the cpp, and friended. This allows the coder to hide a lot of the complexity and internal working of the class from the user of the header.</p>\n\n<p>In the header:</p>\n\n<pre><code>class MyFooPrivate;\nclass MyFoo\n{\n    friend class MyFooPrivate;\npublic:\n    MyFoo();\n    // Public stuff\nprivate:\n    MyFooPrivate _private;\n    // Other private members as needed\n};\n</code></pre>\n\n<p>In the cpp,</p>\n\n<pre><code>class MyFooPrivate\n{\npublic:\n   MyFoo *owner;\n   // Your complexity here\n};\n\nMyFoo::MyFoo()\n{\n    this-&gt;_private-&gt;owner = this;\n}\n</code></pre>\n\n<p>It becomes easier to hide things that the downstream needn't see this way.</p>\n"}, {'answer_id': 365349, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 7, 'selected': False, 'text': '<p>The <code>friend</code> keyword has a number of good uses. Here are the two uses immediately visible to me:</p>\n\n<h2>Friend Definition</h2>\n\n<p>Friend definition allows to define a function in class-scope, but the function will not be defined as a member function, but as a free function of the enclosing namespace, and won\'t be visible normally except for argument dependent lookup. That makes it especially useful for operator overloading:</p>\n\n<pre><code>namespace utils {\n    class f {\n    private:\n        typedef int int_type;\n        int_type value;\n\n    public:\n        // let\'s assume it doesn\'t only need .value, but some\n        // internal stuff.\n        friend f operator+(f const&amp; a, f const&amp; b) {\n            // name resolution finds names in class-scope. \n            // int_type is visible here.\n            return f(a.value + b.value);\n        }\n\n        int getValue() const { return value; }\n    };\n}\n\nint main() {\n    utils::f a, b;\n    std::cout &lt;&lt; (a + b).getValue(); // valid\n}\n</code></pre>\n\n<h2>Private CRTP Base Class</h2>\n\n<p>Sometimes, you find the need that a policy needs access to the derived class:</p>\n\n<pre><code>// possible policy used for flexible-class.\ntemplate&lt;typename Derived&gt;\nstruct Policy {\n    void doSomething() {\n        // casting this to Derived* requires us to see that we are a \n        // base-class of Derived.\n        some_type const&amp; t = static_cast&lt;Derived*&gt;(this)-&gt;getSomething();\n    }\n};\n\n// note, derived privately\ntemplate&lt;template&lt;typename&gt; class SomePolicy&gt;\nstruct FlexibleClass : private SomePolicy&lt;FlexibleClass&gt; {\n    // we derive privately, so the base-class wouldn\'t notice that, \n    // (even though it\'s the base itself!), so we need a friend declaration\n    // to make the base a friend of us.\n    friend class SomePolicy&lt;FlexibleClass&gt;;\n\n    void doStuff() {\n         // calls doSomething of the policy\n         this-&gt;doSomething();\n    }\n\n    // will return useful information\n    some_type getSomething();\n};\n</code></pre>\n\n<p>You will find a non-contrived example for that in <a href="https://stackoverflow.com/questions/356294/is-partial-class-template-specialization-the-answer-to-this-design-problem#356576">this</a> answer. Another code using that is in <a href="https://stackoverflow.com/questions/286402/initializing-struct-using-an-array#287353">this</a> answer. The CRTP base casts its this pointer, to be able to access data-fields of the derived class using data-member-pointers.  </p>\n'}, {'answer_id': 449850, 'author': 'Gorpik', 'author_id': 25824, 'author_profile': 'https://Stackoverflow.com/users/25824', 'pm_score': 2, 'selected': False, 'text': '<p>The short answer would be: use <em>friend</em> when it actually <strong>improves</strong> encapsulation.  Improving readability and usability (operators &lt;&lt; and >> are the canonical example) is also a good reason.</p>\n\n<p>As for examples of improving encapsulation, classes specifically designed to work with the internals of other classes (test classes come to mind) are good candidates.</p>\n'}, {'answer_id': 1388348, 'author': 'larsmoa', 'author_id': 167251, 'author_profile': 'https://Stackoverflow.com/users/167251', 'pm_score': 2, 'selected': False, 'text': "<p>I'm only using the friend-keyword to unittest protected functions. Some will say that you shouldn't test protected functionality. I, however, find this very useful tool when adding new functionality. </p>\n\n<p>However, I don't use the keyword in directly in the class declarations, instead I use a nifty template-hack to achive this:</p>\n\n<pre><code>template&lt;typename T&gt;\nclass FriendIdentity {\npublic:\n  typedef T me;\n};\n\n/**\n * A class to get access to protected stuff in unittests. Don't use\n * directly, use friendMe() instead.\n */\ntemplate&lt;class ToFriend, typename ParentClass&gt;\nclass Friender: public ParentClass\n{\npublic:\n  Friender() {}\n  virtual ~Friender() {}\nprivate:\n// MSVC != GCC\n#ifdef _MSC_VER\n  friend ToFriend;\n#else\n  friend class FriendIdentity&lt;ToFriend&gt;::me;\n#endif\n};\n\n/**\n * Gives access to protected variables/functions in unittests.\n * Usage: &lt;code&gt;friendMe(this, someprotectedobject).someProtectedMethod();&lt;/code&gt;\n */\ntemplate&lt;typename Tester, typename ParentClass&gt;\nFriender&lt;Tester, ParentClass&gt; &amp; \nfriendMe(Tester * me, ParentClass &amp; instance)\n{\n    return (Friender&lt;Tester, ParentClass&gt; &amp;)(instance);\n}\n</code></pre>\n\n<p>This enables me to do the following:</p>\n\n<pre><code>friendMe(this, someClassInstance).someProtectedFunction();\n</code></pre>\n\n<p>Works on GCC and MSVC atleast.</p>\n"}, {'answer_id': 1388412, 'author': 'jalf', 'author_id': 33213, 'author_profile': 'https://Stackoverflow.com/users/33213', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n  <p>edit: Reading the faq a bit longer I like the idea of the &lt;&lt; >> operator overloading and adding as a friend of those classes, however I am not sure how this doesn\'t break encapsulation</p>\n</blockquote>\n\n<p>How would it break encapsulation?</p>\n\n<p>You break encapsulation when you allow <em>unrestricted</em> access to a data member. Consider the following classes:</p>\n\n<pre><code>class c1 {\npublic:\n  int x;\n};\n\nclass c2 {\npublic:\n  int foo();\nprivate:\n  int x;\n};\n\nclass c3 {\n  friend int foo();\nprivate:\n  int x;\n};\n</code></pre>\n\n<p><code>c1</code> is <em>obviously</em> not encapsulated. Anyone can read and modify <code>x</code> in it. We have no way to enforce any kind of access control.</p>\n\n<p><code>c2</code> is obviously encapsulated. There is no public access to <code>x</code>. All you can do is call the <code>foo</code> function, which performs <em>some meaningful operation on the class</em>.</p>\n\n<p><code>c3</code>? Is that less encapsulated? Does it allow unrestricted access to <code>x</code>? Does it allow unknown functions access?</p>\n\n<p>No. It allows precisely <em>one</em> function to access the private members of the class. Just like <code>c2</code> did. And just like <code>c2</code>, the one function which has access is not "some random, unknown function", but "the function listed in the class definition". Just like <code>c2</code>, we can see, just by looking at the class definitions, a <em>complete</em> list of who has access.</p>\n\n<p>So how exactly is this less encapsulated? The same amount of code has access to the private members of the class. And <em>everyone</em> who has access is listed in the class definition.</p>\n\n<p><code>friend</code> does not  break encapsulation. It makes some Java people programmers feel uncomfortable, because when they say "OOP", they actually <em>mean</em> "Java". When they say "Encapsulation", they don\'t mean "private members must be protected from arbitrary accesses", but "a Java class where the only functions able to access private members, are class members", even though this is complete nonsense <em>for several reasons</em>.</p>\n\n<p>First, as already shown, it is too restricting. There\'s no reason why friend methods shouldn\'t be allowed to do the same.</p>\n\n<p>Second, it is not restrictive <em>enough</em>. Consider a fourth class:</p>\n\n<pre><code>class c4 {\npublic:\n  int getx();\n  void setx(int x);\nprivate:\n  int x;\n};\n</code></pre>\n\n<p>This, according to aforesaid Java mentality, is perfectly encapsulated.\n<em>And yet, it allows absolutely anyone to read and modify x</em>. How does that even make sense? (hint: It doesn\'t)</p>\n\n<p>Bottom line:\nEncapsulation is about being able to control which functions can access private members. It is <em>not</em> about precisely where the definitions of these functions are located.</p>\n'}, {'answer_id': 1388471, 'author': 'Gian Paolo Ghilardi', 'author_id': 96081, 'author_profile': 'https://Stackoverflow.com/users/96081', 'pm_score': 2, 'selected': False, 'text': '<p>Another use: <em>friend</em> (+ virtual inheritance) can be used to avoid deriving from a class (aka: "make a class underivable") => <a href="http://www.research.att.com/~bs/bs_faq2.html#no-derivation" rel="nofollow noreferrer">1</a>, <a href="http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.11" rel="nofollow noreferrer">2</a></p>\n\n<p>From <a href="http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.11" rel="nofollow noreferrer">2</a>:</p>\n\n<pre><code> class Fred;\n\n class FredBase {\n private:\n   friend class Fred;\n   FredBase() { }\n };\n\n class Fred : private virtual FredBase {\n public:\n   ...\n }; \n</code></pre>\n'}, {'answer_id': 2245147, 'author': 'garzanti', 'author_id': 271036, 'author_profile': 'https://Stackoverflow.com/users/271036', 'pm_score': 3, 'selected': False, 'text': '<p>The creator of C++ says that isn\'t broking any encapsulation principle, and I will quote him:</p>\n\n<blockquote>\n  <p><strong>Does "friend" violate encapsulation?</strong>\n  No. It does not. "Friend" is an explicit mechanism for granting access, just like membership. You cannot (in a standard conforming program) grant yourself access to a class without modifying its source.</p>\n</blockquote>\n\n<p>Is more than clear...</p>\n'}, {'answer_id': 9909272, 'author': 'Lubo Antonov', 'author_id': 677131, 'author_profile': 'https://Stackoverflow.com/users/677131', 'pm_score': 1, 'selected': False, 'text': "<p>Friend functions and classes provide direct access to private and protected members of class to avoid breaking encapsulation in the general case. Most usage is with ostream: we would like to be able to type:</p>\n\n<pre><code>Point p;\ncout &lt;&lt; p;\n</code></pre>\n\n<p>However, this may require access to the private data of Point, so we define the overloaded operator</p>\n\n<pre><code>friend ostream&amp; operator&lt;&lt;(ostream&amp; output, const Point&amp; p);\n</code></pre>\n\n<p>There are obvious encapsulation implications, however. First, now the friend class or function has full access to ALL members of the class, even ones that do not pertain to its needs. Second, the implementations of the class and the friend are now enmeshed to the point where an internal change in the class can break the friend.</p>\n\n<p>If you view the friend as an extension of the class, then this is not an issue, logically speaking. But, in that case, why was it necessary to spearate out the friend in the first place.</p>\n\n<p>To achieve the same thing that 'friends' purport to achieve, but without breaking encapsulation, one can do this:</p>\n\n<pre><code>class A\n{\npublic:\n    void need_your_data(B &amp; myBuddy)\n    {\n        myBuddy.take_this_name(name_);\n    }\nprivate:\n    string name_;\n};\n\nclass B\n{\npublic:\n    void print_buddy_name(A &amp; myBuddy)\n    {\n        myBuddy.need_your_data(*this);\n    }\n    void take_this_name(const string &amp; name)\n    {\n        cout &lt;&lt; name;\n    }\n}; \n</code></pre>\n\n<p>Encapsulation is not broken, class B has no access to the internal implementation in A, yet the result is the same as if we had declared B a friend of A.\nThe compiler will optimize away the function calls, so this will result in the same instructions as direct access.</p>\n\n<p>I think using 'friend' is simply a shortcut with arguable benefit, but definite cost.</p>\n"}, {'answer_id': 14078313, 'author': 'Ephemera', 'author_id': 1618592, 'author_profile': 'https://Stackoverflow.com/users/1618592', 'pm_score': 2, 'selected': False, 'text': '<p>You have to be very careful about when/where you use the <code>friend</code> keyword, and, like you, I have used it very rarely. Below are some notes on using <code>friend</code> and the alternatives.</p>\n\n<p>Let\'s say you want to compare two objects to see if they\'re equal. You could either:</p>\n\n<ul>\n<li>Use accessor methods to do the comparison (check every ivar and determine equality).</li>\n<li>Or, you could access all the members directly by making them public.</li>\n</ul>\n\n<p>The problem with the first option, is that that could be a LOT of accessors, which is (slightly) slower than direct variable access, harder to read, and cumbersome. The problem with the second approach is that you completely break encapsulation.</p>\n\n<p>What would be nice, is if we could define an external function which could still get access to the private members of a class. We can do this with the <code>friend</code> keyword:</p>\n\n<pre><code>class Beer {\npublic:\n    friend bool equal(Beer a, Beer b);\nprivate:\n    // ...\n};\n</code></pre>\n\n<p>The method <code>equal(Beer, Beer)</code> now has direct access to <code>a</code> and <code>b</code>\'s private members (which may be <code>char *brand</code>, <code>float percentAlcohol</code>, etc. This is a rather contrived example, you would sooner apply <code>friend</code> to an overloaded <code>== operator</code>, but we\'ll get to that.</p>\n\n<p>A few things to note:</p>\n\n<ul>\n<li>A <code>friend</code> is NOT a member function of the class</li>\n<li>It is an ordinary function with special access to the private members of the class</li>\n<li>Don\'t replace all accessors and mutators with friends (you may as well make everything <code>public</code>!)</li>\n<li>Friendship isn\'t reciprocal</li>\n<li>Friendship isn\'t transitive</li>\n<li>Friendship isn\'t inherited</li>\n<li>Or, as the <a href="http://www.parashift.com/c++-faq/friendship-not-inherited-transitive.html" rel="nofollow">C++ FAQ explains</a>: "Just because I grant you friendship access to me doesn\'t automatically grant your kids access to me, doesn\'t automatically grant your friends access to me, and doesn\'t automatically grant me access to you."</li>\n</ul>\n\n<p>I only really use <code>friends</code> when it\'s much harder to do it the other way. As another example, many vector maths functions are often created as <code>friends</code> due to the interoperability of <code>Mat2x2</code>, <code>Mat3x3</code>, <code>Mat4x4</code>, <code>Vec2</code>, <code>Vec3</code>, <code>Vec4</code>, etc. And it\'s just so much easier to be friends, rather than have to use accessors everywhere. As pointed out, <code>friend</code> is often useful when applied to the <code>&lt;&lt;</code> (really handy for debugging), <code>&gt;&gt;</code> and maybe the <code>==</code> operator, but can also be used for something like this:</p>\n\n<pre><code>class Birds {\npublic:\n    friend Birds operator +(Birds, Birds);\nprivate:\n    int numberInFlock;\n};\n\n\nBirds operator +(Birds b1, Birds b2) {\n    Birds temp;\n    temp.numberInFlock = b1.numberInFlock + b2.numberInFlock;\n    return temp;\n}\n</code></pre>\n\n<p>As I say, I don\'t use <code>friend</code> very often at all, but every now and then it\'s just what you need. Hope this helps!</p>\n'}, {'answer_id': 21599285, 'author': 'kiriloff', 'author_id': 1141493, 'author_profile': 'https://Stackoverflow.com/users/1141493', 'pm_score': 0, 'selected': False, 'text': '<p>You may use friendship when different classes (not inheriting one from the other) are using private or protected members of the other class.</p>\n\n<blockquote>\n  <p>Typical use cases of friend functions are operations that are\n  conducted between two different classes accessing private or protected\n  members of both.</p>\n</blockquote>\n\n<p>from <a href="http://www.cplusplus.com/doc/tutorial/inheritance/" rel="nofollow">http://www.cplusplus.com/doc/tutorial/inheritance/</a> .</p>\n\n<p>You can see this example where non-member method accesses the private members of a class. This method has to be declared in this very class as a friend of the class.</p>\n\n<pre><code>// friend functions\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass Rectangle {\n    int width, height;\n  public:\n    Rectangle() {}\n    Rectangle (int x, int y) : width(x), height(y) {}\n    int area() {return width * height;}\n    friend Rectangle duplicate (const Rectangle&amp;);\n};\n\nRectangle duplicate (const Rectangle&amp; param)\n{\n  Rectangle res;\n  res.width = param.width*2;\n  res.height = param.height*2;\n  return res;\n}\n\nint main () {\n  Rectangle foo;\n  Rectangle bar (2,3);\n  foo = duplicate (bar);\n  cout &lt;&lt; foo.area() &lt;&lt; \'\\n\';\n  return 0;\n}\n</code></pre>\n'}, {'answer_id': 28615295, 'author': 'VladimirS', 'author_id': 3545806, 'author_profile': 'https://Stackoverflow.com/users/3545806', 'pm_score': 3, 'selected': False, 'text': '<p>I found handy place to use friend access: Unittest of private functions.</p>\n'}, {'answer_id': 36225178, 'author': 'Shiv', 'author_id': 4843113, 'author_profile': 'https://Stackoverflow.com/users/4843113', 'pm_score': 2, 'selected': False, 'text': '<p>In C++ "friend" keyword is useful in Operator overloading and Making Bridge.<br/><br/>\n1.) Friend keyword in operator overloading :<br/>Example for operator overloading is: Let say we have a class "Point" that has two float variable<br/>"x"(for x-coordinate) and "y"(for y-coordinate). Now we have to overload <code>"&lt;&lt;"</code>(extraction operator) such that if we call <code>"cout &lt;&lt; pointobj"</code> then it will print x and y coordinate (where pointobj is an object of class Point). To do this we have two option:<br/><pre>\n   1.Overload "operator &lt;&lt;()" function in "ostream" class.\n   2.Overload "operator&lt;&lt;()" function in "Point" class.</pre>\nNow First option is not good because if we need to overload again this operator for some different class then we have to again make change in "ostream" class.\n<br/>That\'s why second is best option. Now compiler can call\n<code>"operator &lt;&lt;()"</code> function:<br/></p>\n\n<pre>   1.Using ostream object cout.As: cout.operator&lt&lt(Pointobj) (form ostream class).<br/>   2.Call without an object.As: operator&lt&lt(cout, Pointobj) (from Point class).</pre>\n\n<p>Beacause we have implemented overloading in Point class. So to call this function without an object we have to add<code>"friend"</code> keyword because we can call a friend function without an object.\nNow function declaration will be As:<br/>\n<code>     "friend ostream &amp;operator&lt;&lt;(ostream &amp;cout, Point &amp;pointobj);"</code>\n<br/><br/>\n2.) Friend keyword in making bridge :<br/>\nSuppose we have to make a function in which we have to access private member of two or more classes ( generally termed as "bridge" ) .\nHow to do this:<br/>\nTo access private member of a class it should be member of that class. Now to access private member of other class every class should declare that function as a friend function. For example :\nSuppose there are two class A and B. A function <code>"funcBridge()"</code> want to access private member of both classes. Then both class should declare <code>"funcBridge()"</code> as:<br/>\n<code>   friend return_type funcBridge(A &amp;a_obj, B &amp; b_obj);</code><br/><br/>I think this would help to understand friend keyword.</p>\n'}, {'answer_id': 36486083, 'author': 'peterdcasey', 'author_id': 3702003, 'author_profile': 'https://Stackoverflow.com/users/3702003', 'pm_score': 0, 'selected': False, 'text': '<p>Probably I missed something from the answers above but another important concept in encapsulation is hiding of implementation. Reducing access to private data members (the implementation details of a class) allows much easier modification of the code later. If a friend directly accesses the private data, any changes to the implementation data fields (private data), break the code accessing that data. Using access methods mostly eliminates this. Fairly important I would think.</p>\n'}, {'answer_id': 42187092, 'author': 'Francis Cugler', 'author_id': 1757805, 'author_profile': 'https://Stackoverflow.com/users/1757805', 'pm_score': 0, 'selected': False, 'text': '<p>This may not be an actual use case situation but may help to illustrate the use of friend between classes.</p>\n\n<p><strong>The ClubHouse</strong></p>\n\n<pre><code>class ClubHouse {\npublic:\n    friend class VIPMember; // VIP Members Have Full Access To Class\nprivate:\n    unsigned nonMembers_;\n    unsigned paidMembers_;\n    unsigned vipMembers;\n\n    std::vector&lt;Member&gt; members_;\npublic:\n    ClubHouse() : nonMembers_(0), paidMembers_(0), vipMembers(0) {}\n\n    addMember( const Member&amp; member ) { // ...code }   \n    void updateMembership( unsigned memberID, Member::MembershipType type ) { // ...code }\n    Amenity getAmenity( unsigned memberID ) { // ...code }\n\nprotected:\n    void joinVIPEvent( unsigned memberID ) { // ...code }\n\n}; // ClubHouse\n</code></pre>\n\n<p><strong>The Members Class\'s</strong></p>\n\n<pre><code>class Member {\npublic:\n    enum MemberShipType {\n        NON_MEMBER_PAID_EVENT,   // Single Event Paid (At Door)\n        PAID_MEMBERSHIP,         // Monthly - Yearly Subscription\n        VIP_MEMBERSHIP,          // Highest Possible Membership\n    }; // MemberShipType\n\nprotected:\n    MemberShipType type_;\n    unsigned id_;\n    Amenity amenity_;\npublic:\n    Member( unsigned id, MemberShipType type ) : id_(id), type_(type) {}\n    virtual ~Member(){}\n    unsigned getId() const { return id_; }\n    MemberShipType getType() const { return type_; }\n    virtual void getAmenityFromClubHouse() = 0       \n};\n\nclass NonMember : public Member {\npublic:\n   explicit NonMember( unsigned id ) : Member( id, MemberShipType::NON_MEMBER_PAID_EVENT ) {}   \n\n   void getAmenityFromClubHouse() override {\n       Amenity = ClubHouse::getAmenity( this-&gt;id_ );\n    }\n};\n\nclass PaidMember : public Member {\npublic:\n    explicit PaidMember( unsigned id ) : Member( id, MemberShipType::PAID_MEMBERSHIP ) {}\n\n    void getAmenityFromClubHouse() override {\n       Amenity = ClubHouse::getAmenity( this-&gt;id_ );\n    }\n};\n\nclass VIPMember : public Member {\npublic:\n    friend class ClubHouse;\npublic:\n    explicit VIPMember( unsigned id ) : Member( id, MemberShipType::VIP_MEMBERSHIP ) {}\n\n    void getAmenityFromClubHouse() override {\n       Amenity = ClubHouse::getAmenity( this-&gt;id_ );\n    }\n\n    void attendVIPEvent() {\n        ClubHouse::joinVIPEvent( this-&gt;id );\n    }\n};\n</code></pre>\n\n<p><strong>Amenities</strong></p>\n\n<pre><code>class Amenity{};\n</code></pre>\n\n<p>If you look at the relationship of these classes here; the ClubHouse holds a variety of different types of memberships and membership access. The Members are all derived from a super or base class since they all share an ID and an enumerated type that are common and outside classes can access their IDs and Types through access functions that are found in the base class. </p>\n\n<p>However through this kind of hierarchy of the Members and its Derived classes and their relationship with the ClubHouse class the only one of the derived class\'s that has "special privileges" is the VIPMember class. The base class and the other 2 derived classes can not access the ClubHouse\'s  joinVIPEvent() method, yet the VIP Member class has that privilege as if it has complete access to that event. </p>\n\n<p>So with the VIPMember and the ClubHouse it is a two way street of access where the other Member Classes are limited.</p>\n'}, {'answer_id': 45748046, 'author': 'lixunhuan', 'author_id': 2228340, 'author_profile': 'https://Stackoverflow.com/users/2228340', 'pm_score': 2, 'selected': False, 'text': '<p>As the reference for <a href="http://en.cppreference.com/w/cpp/language/friend" rel="nofollow noreferrer">friend declaration</a> says:</p>\n\n<blockquote>\n  <p>The friend declaration appears in a class body and grants a function or another class access to <strong>private and protected</strong> members of the class where the friend declaration appears.</p>\n</blockquote>\n\n<p>So just as a reminder, there are technical errors in some of the answers which say that <code>friend</code> can only visit <strong>protected</strong> members.</p>\n'}, {'answer_id': 74651861, 'author': 'kaba', 'author_id': 1566112, 'author_profile': 'https://Stackoverflow.com/users/1566112', 'pm_score': 0, 'selected': False, 'text': '<p>Seems I\'m about 14 years late to the party. But here goes.</p>\n<h3>TLDR TLDR</h3>\n<p>Friend classes are there so that you can extend encapsulation to the group of classes which comprise your data structure.</p>\n<h3>TLDR</h3>\n<p>Your data structure in general consists of multiple classes. Similarly to a traditional class (supported by your programming language), your data structure is a generalized class which also has data and invariants on that data which spans across objects of multiple classes. Encapsulation protects those invariants against accidental modification of the data from the outside, so that the data-structure\'s operations (&quot;member functions&quot;) work correctly. Friend classes extend encapsulation from classes to your generalized class.</p>\n<h3>The too long</h3>\n<p>A <em>class</em> is a datatype together with <em>invariants</em> which specify a subset of the values of the datatype, called the <em>valid states</em>. An object is a valid state of a class. A <em>member function</em> of a class moves a given object from a valid state to another.</p>\n<p>It is essential that object data is not modified from outside of the class member functions, because this could break the class invariants (i.e. move the object to an invalid state). <em>Encapsulation</em> prohibits access to object data from outside of the class. This is an important safety feature of programming languages, because it makes it hard to inadvertedly break class invariants.</p>\n<p>A class is often a natural choice for implementing a data structure, because the properties (e.g. performance) of a data structure is dependent on invariants on its data (e.g. <a href="https://en.wikipedia.org/wiki/Red%E2%80%93black_tree" rel="nofollow noreferrer">red-black tree</a> invariants). However, sometimes a single class is not enough to describe a data structure.</p>\n<p>A <em>data structure</em> is any set of data, invariants, and functions which move that data from a valid state to another. This is a generalization of a class. The subtle difference is that the data may be scattered over datatypes rather than be concentrated on a single datatype.</p>\n<h3>Data structure example</h3>\n<p>A prototypical example of a data structure is a <a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)" rel="nofollow noreferrer">graph</a> which is stored using separate objects for vertices (class <code>Vertex</code>), edges (class <code>Edge</code>), and the graph (class <code>Graph</code>). These classes do not make sense independently. The Graph class creates <code>Vertex</code>s and <code>Edge</code>s by its member functions (e.g. <code>graph.addVertex()</code> and <code>graph.addEdge(aVertex, bVertex)</code>) and returns pointers (or similar) to them. <code>Vertex</code>s and <code>Edge</code>s are similarly destroyed by their owning <code>Graph</code> (e.g. <code>graph.removeVertex(vertex)</code> and <code>graph.removeEdge(edge)</code>). The collection of <code>Vertex</code> objects, <code>Edge</code> objects and the <code>Graph</code> object together encode a mathematical graph. In this example the intention is that <code>Vertex</code>/<code>Edge</code> objects are not shared between <code>Graph</code> objects (other design choices are also possible).</p>\n<p>A <code>Graph</code> object could store a list of all its vertices and edges, while each <code>Vertex</code> could store a pointer to its owning <code>Graph</code>. Hence, the <code>Graph</code> object represents the whole mathematical graph, and you would pass that around whenever the mathematical graph is needed.</p>\n<h3>Invariant example</h3>\n<p>An invariant for the graph data structure then would be that a <code>Vertex</code> is listed in its owner <code>Graph</code>\'s list. This invariant spans both the <code>Vertex</code> object and the <code>Graph</code> object. Multiple objects of multiple types can take part in a given invariant.</p>\n<h3>Encapsulation example</h3>\n<p>Similarly to a class, a data structure benefits from <em>encapsulation</em> which protects against accidental modification of its data. This is because the data structure needs to preserve invariants to be able to function in promised manner, exactly like a class.</p>\n<p>In the graph data structure example, you would state that <code>Vertex</code> is a friend of <code>Graph</code>, and also make the constructors and data-members of <code>Vertex</code> private so that a <code>Vertex</code> can only be created and modified by <code>Graph</code>. In particular, <code>Vertex</code> would have a private constructor which accepts a pointer to its owning graph. This constructor is called in <code>graph.addVertex()</code>, which is possible because <code>Vertex</code> is a friend of <code>Graph</code>. (But note that <code>Graph</code> is not a friend of <code>Vertex</code>: there is no need for <code>Vertex</code> to be able to access <code>Graph</code>\'s vertex-list, say.)</p>\n<h3>Terminology</h3>\n<p>The definition of a data structure acts itself like a class. I propose that we start using the term \'generalized class\' for any set of data, invariants, and functions which move that data from a valid state to another. A C++ class is then a specific kind of a generalized class. It is then self-evident that friend classes are the precise mechanism for extending encapsulation from C++ classes to generalized classes.</p>\n<p>(In fact, I\'d like the term \'class\' to be replaced with the concept of \'generalized class\', and use \'native class\' for the special case of a class supported by the programming language. Then when teaching classes you would learn of both native classes and these generalized classes. But perhaps that would be confusing.)</p>\n'}]
['https://Stackoverflow.com/questions/17434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/716/']