What is a Friend Function? Merit and Demerits of Friend Function.



What is a Friend Function? Merit and Demerits of Friend Function.
What is a Friend Function? Merit and Demerits of Friend Function.



Friend Function - A friend function is not a member function but has the full right access to the private member of the class. The friend keyword is used to make a friend function but the function declaration should be preceded by the keyword friend. The function is defined anywhere in the program like a normal function.



Example:

class Sample
{
int a,b;
public:
void getdata()
friend int total(Sample s);
}
void Sample::getdata()
{
a=25;
b=20;
}
int total(Sample s)
{
return(s.a+s.b);
}
int main()
{
Sample obj;
obj.getdata();
count<<"Total="<<total(obj);
return 0;
}



Output:

Total =45




Merits of friend function

  1. While defining the friend function, there is no need to use the scope resolution operator as friend keyword.
  2. The friend can be defined anywhere in the program similar to normal function.
  3. It can be invoked like a normal function without the help of any object.
  4. A function may be friend of more than one class. 

Demerits of friend function

  1. The friend function is declared in the class but it, not a member function of class. To access the private data members of class it is necessary to create objects.
  2. When a function is friend of more than one class then forward declaration of class is needed


Post a Comment

0 Comments