Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friend functions in C++

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.

like image 744
Kundan Kumar Avatar asked Jun 19 '12 19:06

Kundan Kumar


People also ask

What is friend function in C with example?

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.

What is a friend function?

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.

What is a friend function give example?

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.


1 Answers

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.

like image 150
Jerry Coffin Avatar answered Nov 02 '22 05:11

Jerry Coffin