In a C++ program, when a function is defined as a friend function, then the private and protected data of the class can be accessed from that function. This is because the compiler knows a given function is a friend function by its keyword friend.
Friend function declaration should be made inside the body of class (though, it can be done anywhere inside a class, either in private or public section) starting with the keyword friend.
Syntax:
class class_name
{
...... .... ........
friend return_type function_name(arguments);
...... .... ........
}
Therefore, you can define the friend function of that name, and that function can access the private and protected data of the function. However, no keywords are used in the function definition of the friend function.
Example:
#include <iostream>
class Distance
{
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
int func(Distance d) //function definition
{
d.meter=5; //accessing private data from non-member function
return d.meter;
}
void main()
{
Distance D;
cout<<"Distace: "<<func(D);
getch();
}