Friend Function in C++


Prev Tutorial Next Tutorial

Friend Function in C++

In C++ a Friend Function that is a "friend" of a given class is allowed access to private and protected data in that class.

A function can be made a friend function using keyword friend. Any friend function is preceded with friend keyword. The declaration of friend function should be made inside the body of class (can be anywhere inside class either in private or public section) starting with keyword friend.

Why use friend function ?

You do not access private or protected data member of any class, to access private and protected data member of any class you need a friend function.

Syntax

class class_name
{
 ......
 friend returntype function_name(arguments);
}

Friend class

Similarly like, friend function a class can be made a friend of another class using keyword friend.

Syntax

class A 
{
  friend class B; // class B is a friend class
  ......
}
class B
{
  ......
}

When a class is made a friend class, all the member functions of that class becomes friend function.

If B is declared friend class of A then, all member functions of class B can access private and protected data of class A but, member functions of class A can not private and protected data of class B.

Note: Remember, friendship relation in C++ is always granted not taken.

Example Friend function

In below example you can access private function of class employee by using friend function.

Example

#include<iostream.h>
#include<conio.h>

class employee
{
private:
       friend void sal();
};

void sal()
{
int salary=4000;
cout<<"Salary: "<<salary;
}

void main()
{
employee e;
sal();
getch();
}

Output

Salary: 4000

Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements