CPP Programming
About Lesson

The friend function is an outsider that has access to the private members of a class.  The friend keyword is to be prefixed to declare a friend function within the class.  The definition of friend function can be elsewhere like normal function.  A function can be friend to many classes.

Characteristics of friend functions:

  • It is not the member of the class to which it is friend
  • It cannot be called by object, since it is not a member.  It should be invoked as normal function
  • It can not directly refer members of class.  It should use object to access members
  • It can be declared either in the public or private area of a class without affecting its meaning
  • Usually, it has objects as arguments.

//Example program for Friend Functions
#include<iostream.h>
class sample
{
int a,b;
public:
void setvalue(){a=25;b=40;}
friend float mean(sample s); //declaration of friend
};
float mean(sample s)
{
return float(s.a+s.b)/2;
}
main()
{
sample x;
x.setvalue();
cout<< “Mean value:” <<mean(x)<< “\n”;
}

You cannot copy content of this page