What is friend function? Explain the use with an example.

Friend Function:

Friend functions are those functions which can access all the functions and  variables of a class though it is not a member function of that class. Actually to share a function among two or more classes friend functions are used. If it is declared so, then it will able to access all variables and functions of those classes.

Explanation with Example:

An explanation can be given using the following program with required comments,

//friend function

class cls2; //this is forward declaration of class cls2

class cls1{
int a; //this ‘a’ is for objects of class cls1
void set_a(){
a=4; //setting ‘a’ for objects of class cls1
friend void sum(cls1, cls2);

class cls2{
int a; //this ‘a’ is for objects of class cls2
void set_a(){
a=4; //setting ‘a’ for objects of class cls2
friend void sum(cls1, cls2);

void sum(cls1 x, cls2 y){
cout<<x.a+y.a; /*printing the summation of the value of ‘a’
*under the object ‘ob1’ of class cls1 and
*the value of ‘a’ under the object
*‘ob2’ of class cls2

void main(){
cls1 ob1;
cls2 ob2;

ob1.set_a(); //calling the set_a() function of class cls1 by ob1
ob2.set_a(); //calling the set_a() function of class cls2 by ob2
sum(ob1, ob2); /*calling the friend function sum(cls1, cls2) which
*is common in both the classes cls1 and cls2 and
*thats why it can operate on the variables of
*both the classes.


            Output: 8
Here taking two classes cls1 and cls2 and having a friend function sum(cls1, cls2). In the main() creating two objects each for each class. Now through the objects of the classes calling their own set_a() function. Now at last calling the friend function sum(cls1, cls2). Here we are passing the two objects of the two different classes created previously to this friend function. It is operating on both of them and printing the summation.

Use of Friend Function:

Some uses of the friend given below can be found,

  1. When certain operator overloading is required friend functions can be useful.
  2. Friend function makes the creation of some types of I/O functions easier.
  3. Sometimes two or more classes may contain interrelated members which may need to be operated at a time. In such times a friend function is required.


No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published.