Hi programmers!

I am trying to grasp the concept of friendship.

Let's say that we have the following:

class List; //forward declaration

class ListNode
{
    friend class List;  //make List a friend

    /*
        rest of code here, blah, blah, blah.
    */
}

Does this mean that ListNode can access Lists's private members and List cannot access ListNode's private members, or both classes can access each others private members conversely?

Recommended Answers

All 3 Replies

Does this mean that ListNode can access Lists's private members

No, it's the other way around. By declaring List as a friend, the ListNode class gives access to its private members to the List class. It's like an invitation, ListNode invites List into its access-space.

Just think about it as a house. ListNode has a house with private things in it. It declares List as its friend, like giving List the keys to its house and thus access to its private things.

If it were to work the other way (as in, "ListNode can access List's private members"), then it would be the equivalent of ListNode declaring itself the friend of List and inviting itself into List's house. You can't do that, just like you cannot walk up to some stranger's front door and declare yourself their friend and invite yourself in. It always works the other way, they invite you in.

To add on to what Mike said, just remember "only friends can see your private parts".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.