Sunday 29 March 2015

Friend Functions with Two Classes

Consider a situation of operating on objects of two different classes. In such a situation, friend functions can be used to bridge the two classes.

Sample program

#include <iostream.h>
class two;
class one
{
int data1;
public:
void setdata(int init)
{
data1 = init;
}
friend int add(one a, one b);
};
class two
{
int data2;
public:
void setdata2(int init)
{
data2 = init;
}
friend int add(one a, one b);
};
int add(one a, one b)
{
return a.data1 + b.data2;
}
void main()
{
one a;
two b;
a.setdata(10);
b.setdata(20);
cout<<”Sum of one and two is”<<add(a,b);
}

observe the following declaration at the beginning of the program

class two;

it is necessary, since a class cannot be referred until it has been declared before the class one. It informs the compiler that the class two’s specification will appear later.

Though friend functions, add flexibility to the language and make programming convenient in certain situations, they are controversial; it goes against the philosophy that only member functions can access a class’s private data. Friend functions are useful in certain situations. One such example is when a friend is used to increase the versatility of overloaded operators.

Friend functions are useful in the following situations

? Function operating on objects of two different classes. This is the ideal
   situation where the friend function can be used to bridge two classes.
? Friend functions can be used to increase the versatility of overloaded
   operators.
? Sometimes, a friend allows a more obvious syntax for calling a function,
   rather than what a member function can do.


No comments:

Post a Comment