A
friend function of a class is defined outside that class scope but it has the
right to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not
member functions.
To
declare a function as a friend of a class, precede the function prototype in
the class definition with keyword friend.
class ABC
{
….
public:
….
friend void
xyz();
}
Friend function characteristics
1.It is not in the scope of the class to which it has been declared as friend.
2.Since it is not in the scope of the class, it cannot be called using object of that class.
3.It can be invoked like a normal function without the help of any object.
4.Unlike member functions, it cannot access the member names directly and has to use an object name and dot membership operator with each member name (e.g. A.x).
5.It can be declare either in the public or the private part of the class without affecting its meaning.
6.Usually, it has the object as arguments.
Example:
Friend Function
#include<iostream.h>
#include<conio.h>
class sample
{
int a,b;
public:
void setvalue()
{
a=26;
b=63;
}
friend float mean(sample s);
};
float
mean(sample s)
{
return float(s.a+s.b)/2.0;
}
int
main()
{
sample x;
x.setvalue();
cout<<"Mean value is
“<<mean(x);
return 0;
}
For Complete C++ Training in Gwalior







