C++ Friend Function

Friend function is a special function which is not a member of some class but it can access private as well as protected members of class.

Features Of Friend function:


  • Function my be declared friend more than one class.
  • It can be invoked like a normal function.
  • It depends on its original declaration and definition.

Syntax


class class_name
{
     private:
     //
     friend return_type function_name(Argument);
};
return_type function_name(Argument)
{
}

Program to show fiend function.



#include<iostream.h>
#include<conio.h>
class data
{
  int a;
  public:
   void readshow()
   {
       a =10;
       cout<<"\nValue Of a="<<a;
   }
   friend void display(data obj);
};
void display(data obj)
{
   cout<<"\nValue from friend function a="<<a;
}
void main()
{
    clrscr();
    data d;
   d.readshow();
   display(d);
    getch();
}



Output

Value of a =10
Value from friend function a= 10

Back To Top