Friend functions
The major concept of the OOPs is data encapsulation and data hiding. Whenever data variables are declared in a private type of a class these members are restricted from accessing through non-member functions. To access a private data member through a non-member function is to modify a private data member to a public group. Whenever the private or protected data member is modified to a public category, it violates the overall concept of data hiding and data encapsulation. To explain this problem, a friend function can be declared to have access to these data members. Friend is a particular mechanism for letting non-member functions access private data. A friend function might be declared or defined inside the scope of a class definition. A keyword friend informs the compiler in which it is not a member function of the class.
The general form is
friend function return_type user_function_name(parameters);
where friend is a keyword that is used as function modifier.
Example:
class alpha
{
private:
int x;
public:
void getdata( );
friend void display (alpha abc);
{
cout<<"value of x = "<<abc.x;
cout<< endl;
}
};
void sample :: getdata ( )
{
cout<<"enter value for x \n";
cin>>x;
}
void main ( )
{
alpha a;
a.getdata ( );
cout<<"accessing private data by non-member function"<<endl;
display(a);
}