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

Advertisements

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

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

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

Download Projects

Google Advertisements


Buy Websites 9999595223

Buy Fresh and Payment Receive Media.net Account with Website. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements