Friend declaration in C++ - difference between public and private

C++PrivateFriendPublic

C++ Problem Overview


Is there a difference between declaring a friend function/class as private or public? I can't seem to find anything about this online.

I mean the difference between:

class A
{
 public: 
      friend class B;
 };

and

class A
{
 private: //or nothing as the default is private
      friend class B;
 };

Is there a difference?

C++ Solutions


Solution 1 - C++

No, there's no difference - you just tell that class B is a friend of class A and now can access its private and protected members, that's all.

Solution 2 - C++

Since the syntax friend class B doesn't declare a member of the class A, so it doesn't matter where you write it, class B is a friend of class A.

Also, if you write friend class B in protected section of A, then it does NOT mean that B can access only protected and public members of A.

Always remember that once B becomes a friend of A, it can access any member of A, no matter in which section you write friend class B.

Solution 3 - C++

c++ has the notion of 'hidden friends': http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1601r0.pdf

Which only applies to friend functions that are defined inline. This make it so the functions can only be found via argument-dependent lookups, removing them from enclosing namespace.

Solution 4 - C++

The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears.

As such access specifiers have no effect on the meaning of friend declarations (they can appear in private: or in public: sections, with no difference).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBIUView Question on Stackoverflow
Solution 1 - C++sharptoothView Answer on Stackoverflow
Solution 2 - C++NawazView Answer on Stackoverflow
Solution 3 - C++Alfred FullerView Answer on Stackoverflow
Solution 4 - C++goyuiitvView Answer on Stackoverflow