Friend function in C++ | Friend class in C++



Friend function in C++ | Friend class in C++

Friend Function in C++

Friend function in C++ is a special kind of function which is not a member of some class but it can access private as well as protected members of a class in indirect manner.

Working of Friend function in C++

A non member function of a class can be declared as friend by prefixing function declaration with keyword friend inside the class.

We can write the body of friend function anywhere inside the program but we don’t need keyword friend with it again.

We don’t need to use object of the class to access friend functions as they are not member functions of a class.

 Features

  • A function can be friend of multiple classes.
  • We don’t need an object to call a friend function. 
  • It can be declared anywhere in the class without effecting its meaning.
  • Friend function can work with private and protected members of a objects passed as arguments to it.
//Program to demonstrate friend function 
#include<iostream>
using namespace std;
class demo
{
  int num;
public:
  void readshow()
  {
   cout<<”\nEnter value of num=”;
   cin>>num;
   cout<<”\nWithin member function num=”<<num;
  }    
  friend void display(demo obj);  //Friend function declaration
};
void display(void obj)  //Friend function body
{
  cout<<endl<<”Within friend function a=”<<obj.a;
}
int main()
{
  demo d1;
  d1.readshow();
  display(d1);
  return 0;
}

Output

Enter value of num=15
Within member function a=15
Within friend function a=15

Friend class in C++

Friend class in C++ is a class whose member functions can access private and protected members of another class.

We can make a class a friend of another class by declaring it in another class prefixing  with the keyword friend.

We need to use the object of friend class to access the private and protected members of the friend class. 

//Program to demonstrate friend class
#include<iostream>
using namespace std;
class demo; //class demo has been declared here because it is defined after class data.
class data
{
  int x;
  float y;
public:    
     void read()
     {
      cout<<”\nEnter value of x=”;
      cin>>x;
      cout<<”\nEnter value of y=”;
      cin>>y;
}
  friend class demo;
};
class demo
{
 public:
     void show(data obj)
     {
       cout<<endl<<obj.x<<”,”<<obj.y;
     }
};
int main()
{
  data d1;
  d1.read();
  demo d2;
  d2.show(d1);
  return 0;
}
Output
Enter value of x=15
Enter value of y=5
15,5



Spread the love
Lesson tags: Friend class in C++, Friend function in C++, Program of Friend class in C++, Program of friend function in C++
Back to: C++ Programming Notes
Spread the love