In C++ friend function is a kind of function that is a "friend" of a given class is allowed access to private and protected data in that class that it would not normally be able to as if the data was public.
Wiki
A friend function in a C++
class is defined outside the scope of a class but it has the right to access all private
and protected
members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.
To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows
Example
// friend_functions.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class Point
{
friend void ChangePrivate( Point & );
public:
Point( void ) : m_i(0) {}
void PrintPrivate( void ){cout << m_i << endl; }
private:
int m_i;
};
void ChangePrivate ( Point &i ) { i.m_i++; }
int main()
{
Point sPoint;
sPoint.PrintPrivate();
ChangePrivate(sPoint);
sPoint.PrintPrivate();
}
Tag usage
The tag friend-function can be used for programming related problems in implementation of friend functions, Theoretical questions such as "How to use friend functions" should be avoided