Is there a way to access the private members of a class by a non member function?. Well there is one way, know as the friend function. This function has access to all private and protected members of the class for which it is a friend.

To declare a friend function, include its prototype in the class of which you want to access the private and public members, preceding it with the keyword friend.



using namespace std;
class myclass
int a,b;
friend int sum(myclass x);
void set_ab(int i, int j);

The function sum is not a member function of any class. Although sum is not a member, it still has full access to its private members.

The friend functions are not called by the reference of the object created by the class, because it is not a member of the class, so it cannot be qualified with an objects name.

int main()
myclass n;
n.set_ab(3,4);//Call by the reference of the object.
sum(n);//Directly called without reference of the object.

So we can access all the members of a class by a non-member function, if the function is a friend with the class.