Characteristics of Friend Function in C++

Friend Function in C++:

In C++, It allows the common function to be made friendly with both classes. It allows the function to have access to the private data of these classes. These functions are called friend functions. It can be declared as a friend in any number of classes. It has the following Syntax:

class test
{
........
........
public:
........
........
friend void temp(void); // declaration
};

Characteristics of Friend Function:

1. It’s not in the scope of the class to which it has been declared as a friend.
2. It can be invoked like a normal function without the help of any object.
3. It can’t be called using the object of that class.
4. It can’t access the member names directly and it has to use an object name and dot membership operator with each member name.
5. It has objects as arguments.
6. It can be declared either in the public or the private part of the class without affecting its meaning.

Program:

#include<iostream.h>
#include<conio.h>
using namespace std;
class test
{
int x, y;
public setvalue(){x=20; y=25;}
friend float mean(sample s1);
};
float mean(sample s1)
{
return float(s1.x+s1.y)/2.0;
}
int main()
{
sample sp;
sp.setvalue();
cout<<"Mean Value="<<mean(sp);
return 0;
}

Output:
Mean Value= 22.5