friend function in c++


Friend function:
Friend function access all private and protected data member of the class when it has a friend. To declared as friend function, must include it’s prototype within the class and also include keyword friend.

Ex:

#include <iostream>
Using namespace std;
Class sum
{
Int a,b;
Public:
Friend int sum(); // declared as friend
Void set_ab(int i,int j);
};
Void sum :: set_ab(int I,int j)
{
a=i;
b=j;
}
Int sum() /* because we declared sum()is friend of class sum, direct access a and b */
{
Int x;
x.a + x.b;
}
Int main()
{
Sum s;
s.set_ab(20,30);
cout<<return 0;
}

You can notice that sum() is not a member of class sum, but it still all rights to access its private members, and also noticed that the sum() is called without use of dot operator.

Recommended Posts:

Post a Comment

2 Comments