Friend Function in C++

Friend Function

 
Here, in this section we will discuss about friend function in C++.

Definition: A friend function is capable to access the private/protected data of a class in which it is declared as a friend, though it is a nonmember function of that class

Basic properties of friend

  • A function can be declared as a friend to any number of classes
  • A friend function tough not a member function has full rights and access to the members of the class

`

friends function in C++

Creating a friend function

Run

#include<iostream>
using namespace std;
class demo
{
  private:
  int a=5;
  friend void display(demo);//friend function declaration
};
void display(demo d)//friend function defination
{
  cout<<"a: "<<d.a<<endl;//access of private data
}
int main()
{
  demo d;
  display(d);//calling a friend function
return 0;
}

O/P

a:4

In the above code display() function is made friend with demo class so that display() function can access the private data of the class demo

Friend class

  • A class  declared with a friend with another class is able to access private/protected  data members of that class
  • When a class is made a friend class, all the member functions of that class becomes friend functions to that class

Creating friend class

  • In this program, all member functions of class test2 will be friend functions of class test1.
  • Thus, any member function of class test2 can access the private and protected data of class test1.
  • But, member functions of class test1 cannot access the data of class test2.
Run
#include<iostream>
using namespace std;
class test1
{
  int a,b;
  public:
  void get()
  {
   cout<<"enter 2 integers";
   cin>>a>>b;
  }
  friend class test2;//defining friend class
};
class test2
{
   test1 t1;
   public:
   void put()
  {
      t1.get();
      cout<<"a: "<<t1.a<<endl;
       cout<<"b: "<<t1.b<<endl;
   }
};
main()
{
    test2 t2;
    t2.put();
}
O/P
enter 2 integers 3  4
a:3
b:4

Advantages

Code reusability: instead of creating separate member functions to access private data of each class ,a single member function can access private data of many classes

Disadvantages

Security: friend functions should be used only when absolutely necessary because friend mechanism alters the security of private data which is against data hiding

Real-time applications of Friend

  • Device integration is possible only by  friend
    ex: GPRS, Satellite communication
  • Friend class is also used in APIs(Application Programming Interface)
    ex: money transfer from one bank to another

Note:

Java and Unix System never support Friend Mechanism