Friend Function ➢ We know that the private member cannot be accessed from outside the class. That is, a non-
member-function cannot have an access to private data of a class. However, there could be a
situation where we would like two classes to share a particular function. In such situation C++
allows the common function to be made friendly with both the classes, thereby allowing the
function to have access to the private data of these classes. Such a function need not to be a
member of any of these classes.
➢ To make outside function “friendly” to a class, we have to simply declare this function as a
friend of the class as shown below :
Class ABC
{
………..
…………
public:
……………
…………..
15
Friend void xyz(void); //declaration
};
➢ The functions that are declared with the keyword friend are known as friend functions.
➢ A function can be declared as friend in any number of classes.
➢ A friend function, although not a member function, has full access rights to the private members
of the class.
A friend function possesses certain special characteristics:
1) It is not in the scope of the class to which it has been declared as friend.
2) Since it is not in the scope of the class, it cannot be called using the object of that class.
3) It can be invoked like a normal function without the help of any object.
4) Usually, it has objects as arguments.
5) It cannot access the member names directly and has to use an object name and dot
membership operator with each member name (e.g A.x)
Example: #include using namespace std;
class sample
{
int a;
int b;
public:
void setvalue( ) { a=25;b=40;}
friend float mean( sample s);
};
float mean (sample s)
{
return (float(s.a+s.b)/2.0);
}
int main ( )
{
sample x;
x . setvalue( );
cout<<"mean value="<return(0);
}
Member functions of one class can be friend function of another class. In such cases, they are defined
using the scope resolution operator.
16
E.g.
class X
{
………..
………..
int fun1( ); //member function of x
………..
};
class Y
{ …………..
……………
friend int x : : fun1( ); //fun1 ( ) of X is friend of Y
};
Here, fun1( ) is a member of class X and friend of class Y