Friend Function in C++

Google 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 Advertisements

Buy This Ad Space @$50 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

Cloud computing is the on demand availability of computer system resources, especially data storage and computing power, without direct active management by the user. Cloud Computing Tutorial

College Projects Related to Java, AWT, C Projects for College, C++ Projects for College, Android Projects. Download Java C C++ Projects

Download Projects

Adsense Advertisements


Buy This ads Space 8076671483

Buy This Ad Space @$120 per Month, Ad Size 300X600 Contact on: hitesh.xc@gmail.com or 8076671483 Try this Keyword C++ Programs