First, have a look at the following code:
// Using Friend Functions
#include <iostream.h>
class myclass
{
int a;
public:
friend int geta(myclass);
void seta(int x){a=x;}
};
// notice how the friend function
// can access even the private members
// of the class
int geta(myclass ob)
{
return ob.a;
}
void main()
{
myclass obj;
obj.seta(100);
// accessed as usual
cout<<geta(obj);
}
Did you notice the specialty?
In the above example program the function geta() is just a general function (friend of class, of course) but still it is able to access the private member of the class (i.e. the variable ‘a’). The function is also called as usual since it is not a member function.
This is because by declaring any non-member function as friend inside a class, gives it access to the entire Private and Protected members of that class.
Many of you would be wondering what is gained by doing this all?
The answer is that there are circumstances when its use simplifies certain operations, it is also widely used in overloading operators besides this there are some other uses of friend functions none of which can be discussed here, so we leave the use friend functions for future articles!
Related Articles: