I have a doubt related to friend functions in C++. Friend function is not a member function of the claas and can be invoked directly from the main. So, what difference does it make if we keep the friend
function within the private
or the public
part of the class
. I have generally noticed that the friend
functions are always in the public part. In what scenario we should keep the friend
function within private
.
Friend class and function in C++ For example, a LinkedList class may be allowed to access private members of Node. A friend class can access both private and protected members of the class in which it has been declared as friend.
A friend function is used to access all the non-public members of a class. You can use a friend function to bridge two classes by operating objects of two different classes. It increases the versatility of overloading operators. It enhances encapsulation.
In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that is given the same access as methods to private and protected data. A friend function is declared by the class that is granting access, so friend functions are part of the class interface, like methods.
The compiler does not pay any attention to whether a friend function is in the private or public (or protected) section of a class. Most people put it in the public section, but it'll be publicly visible regardless of where you put it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With