Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can friend function be declared in private?

A friend function can be declared in the private or public section of the class. It can be called like a normal function without using the object. A friend function is not in the scope of the class, of which it is a friend. A friend function is not invoked using the class object as it is not in the scope of the class.

Does it make any difference if we define friend function under public or private section?

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.

Is a private member of friend class?

A friend class in C++ can access the private and protected members of the class in which it is declared as a friend. A significant use of a friend class is for a part of a data structure, represented by a class, to provide access to the main class representing that data structure.


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.


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.


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.