There is mechanism built in C++ programming to access private or protected data from
non-member function which is friend function and friend class.
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 as follows:
FRIEND FUNCTION
#include<iostream.h>
#include<conio.h>
class sum
{
inta,b;
public:
voidget_ab()
{
cout<<"enter the values of a and b:";
cin>>a>>b;
}
friend void add(sum s);
};
void add(sum s)
{
cout<<"\n sum of a and b is:"<<s.a+s.b;
}
void main()
{
clrscr();
sum s1;
s1.get_ab();
add(s1);
getch();
}
FRIEND FUNCTION
#include<iostream.h>
#include<conio.h>
class testing
{
inta,b;
public:
voidget_ab()
{
cout<<"enter values of a and b:";
cin>>a>>b;
}
friendint max(testing t1);
};
int max(testing t1)
{
if(t1.a>t1.b)
{
return t1.a;
}
else
{
return t1.b;
}
}
void main()
{
clrscr();
testingobj;
obj.get_ab();
cout<<"MAXIMUM VALUE IS:"<<max(obj);
getch();
}