How Friend function works as a bridge between classes

A Friend function can be used as a common function between two classes as it can become a friend of both the classes and can use their private data.

#include<iostream.h>
class b; //forward declaration
class a
{
         int m;
         public: void getdata(int t)
         { 
                    m=t; 
          }
         void display()
         {
                 cout<<m<<"\n"; 
          }
         friend void swap(a &, b &);
};

class b
{
         int n;
         public:
         void getdata(int t)
        { 
                 n=t; 
         }
         void display()
        { 
                  cout<<n;
         }
         friend void swap( a &,b &); 
};
void swap( a &x, b &y)
{
        int temp;
        temp=y.n;
        y.n=x.m;
        x.m=temp;
}
void main()
{
        a x1;
        b x2;
        x1.getdata(100);
        x2.getdata(200);
        swap(x1,x2);
        x1.display();
        x2.display();
}

Sample Output:


Post a Comment

Previous Post Next Post