Friend Function in C++

Advertisements

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

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements