a friend function is used to allow access to its private data from a non-member function.this is achieved by declaring the non-member a friend.
Once a non-member function is declared as a friend, it can access the private data of the class. Similarly when a class is declared as a friend, the friend class can have access to the private data of the class t which it is a friend.
example ::
Code:
#include <iostream.h>
//Declaration of the function to be made as friend for the C++ Tutorial sample
int AddToFriend(int x);
class Tutorial
{
int private_data;
friend int AddToFriend(int x);
public:
Tutorial()
{
private_data = 5;
}
};
int AddToFriend(int x)
{
Tutorial var1;
return var1.private_data + x;
}
int main()
{
cout << "Added Result for this C++ tutorial: "<< AddToFriend(4)<<endl;
}
This will give an output of ::
Added Result for this C++ tutorial: 9
C++ tutorial - friend class:
Declaration of a friend class is also similar. Only thing is a class definition is slightly different.
Code:
#include < iostream.h >
class Tutorial
{
int private_data;
friend class friendclass;
public:
Tutorial()
{
private_data = 5;
}
};
class friendclass
{
public:
int subtractfrom(int x)
{
Tutorial var2;
return var2.private_data - x;
}
};
int main()
{
friendclass var3;
cout << "Added Result for this C++ tutorial: "<< var3.subtractfrom(2)< }
The output of the above C++ Tutorial sample will be
Subtracted Result for this C++ tutorial: 3
This is a good way out given by C++ to avoid restrictions on private variables. But this should be used with caution though. If all the functions and classes are declared as friends, then the concept of encapsulation will be overlooked.