Friend Function


A friend function is a function that is not a member of a class but it can access private and protected member of the class in which it is declared as friend.
Since friend function is not a member of class it can not be accessed using object of the class. It is called in the same way as normal external function is called.
It works same as your real life friend. Your friend is not a member of your family but still he knows about you and your family.
Sometimes it is required that private member of the class can be accessed outside the class at that time we have to use friend function.
A function can be declared as a friend by preceding function declaration with friend keyword as shown below:
friend Return_Type Function_Name (Argument List);

     

Example:
#include<iostream.h>
class Circle
{
int r;
public:
void input()
{
cout<<"Enter Radius:";
cin>>r;
}
friend float area(Circle C);
};
float area(Circle C)
{
return (3.14*C.r*C.r);
}
int main()
{
Circle C1;
C1.input();
cout<<"Area of Circle is:"<<area(C1);
return 0;
}

Friend function having following characteristics:
(1) A friend function can be declared inside class but it is not member of the class.
(2) It can be declared either public or private without affecting its meaning.
(3) A friend function is not a member of class so it is not called using object of the class. It is called like normal external function.
(4) A friend function accepts object as an argument to access private or public member of the class.
(5) A friend function can be declared as friend in any number of classes.

Download Projects


Download Programs