Friend Function in C++
Introduction
- Friend functions are special functions of C++ and considered to be a loophole in the Object Oriented Programming concepts.
- Friend function is defined by its keyword friend.
- Private and Protected data of class can be accessed using friend function.
- It is defined inside the body of class either in private or public section.
- When we define friend function, the entire class and all of its members are friends.
Syntax:
class class_name
{
friend return_type function_name(arguments);
}
Example : Demonstrates the working structure of Friend function
#include <iostream>
using namespace std;
class Employee
{
private:
int empid;
public:
Employee(): empid(0){ }
friend int display(Employee); //friend function
};
int display(Employee e) //function definition
{
e.empid = 100; //accessing private data from non-member function
return e.empid;
}
int main()
{
Employee e;
cout<<"Employee Id: "<<display(e);
return 0;
}
Output:
Employee Id: 100
In the above program, friend function
display() is declared inside Employee class. So, the private data can be accessed from this function.
Friend Class
- Friend class is similar to friend function.
- Friend class is defined by using friend keyword.
- It increases encapsulation due to interdependency between the classes.
- It has full access of private data members of another class without being member of that class.
Syntax:
class class_name
{
friend class class_name2; //class_name2 is a friend class
}
class class_name2
{
//Statements;
}
All the member functions of another class can be accessed using friend class.
Example : Demonstrating the basic structure of Friend class
class A
{
friend class B; // Class B is a friend class
}
class B
{
//Statements;
}
In the above example, all the member functions of
class B will be friend function of class B. So, any member function of
class B can
access the private and protected data of class A, but member functions of
class A cannot private and protected data of class B.