Friend Function in C++ with example



Friend function is basically used to access the private information about the class.
When we use friend function we should declare in the class as a friend function in the following manner.

Friend return_datatype function_name (arguments);

There are the following situations in which the friend function needed.
·        Function operating on objects of two distinct classes.
·        Friend function can be used to increase the versatility of overloaded operators.
·        Sometimes, a friend allows a more clear syntax for calling a function rather than what a member function can do.

Example:
#include<iostream.h>
#include<conio.h>
Class employee
               {
                              int id;
                              char name[20];
                              public:
                              void getdata();
                              friend void putdata();
               };
void employee :: getdata()
{
cout<<”Enter the employee id & name =”;
cin>>id>>name;    
}
void employee :: putdata(employee t)
{
               cout<<” Employee Id = ”<<t.id;
               cout<<” Employee Name = ”<<t.name;
}
void main()
{
   clrscr();
               employee e;
               e.getdata();
               putdata(e);
               getch();
}

No comments:

Post a Comment