06 Desember, 2009

Friend Function

Concept 
When a function needs to operate on private data in objects two different classes, the function can be declared as a friend in each of the classes, taking objects of the two classes as arguments.
// A common friend function to exchange the private values of two classes
#include <iostream.h>
class A;
class B; 

class A 

  private:
    int value1;
  public: 
    void in(int a)
    {
       value1=a;
    }
   void display()
   {
       cout<< value1;
   }
   friend void exchange(A&, B&); 
 }; 

class B 

   private:
     int value2;
   public:
     void in(int a) 
     {
        value2=a; 
     } 
     void display()
     {
        cout<< value2; 
     }
     friend void exchange (A&, B&); 
}; 

void exchange(A& x, B& y) 
{
   int temp=x.value1;
   x.value1=y.value2; 
   y.value2=temp; 


int main()

   A obj1;
   B obj2;
   obj1.in(1000);
   obj2.in(2000);
   cout<<"\n Before";
   obj1.display();
   obj2.display();
   cout<<"\n After";
   exchange(obj1, obj2);
   obj1.display();
   obj2.display();
   return 0;
}


Example
The following is an example of friend function's usage. The function show() is a friend of classes A and B which is used to display the private members of A and B. Instead of writing a separate function in each of the classes only one friend function can be used to display the data items of both the classes.
//Example - 1
#include<iostream.h>  
using namespace std; 

class B; // Forward declaration of class B in order for example to compile 

class A 
{
  private: 
    int a;
  public: A() 
  { 
    a=0; 
  } 
  friend void show(A& x, B& y); 
}; 

class B 

   private: 
     int b; 
   public:
    B()
    {
      b=6;
    }
    friend void show(A& x, B& y);
}; 
void show(A& x, B& y) 
{
   cout << "A::a=" << x.a << endl;
   cout << "B::b=" << y.b << endl;
}

int main() 
{
   A a;
   B b;
   show(a,b);


//Example - 2
#include<iostream.h>
using namespace std; 

class B; // Forward declaration of class B in order for example to compile 

class A 
{
  private:
    int a;
  public: 
    A() 
    {
       a=0; 
     } 
     void show(A& x, B& y); 
}; 

class B 
{
   private:
     int b;
   public:
     B()
     {
       b=6;
     }
     friend void A::show(A& x, B& y);
};

void A::show(A& x, B& y)
{
   cout << "A::a=" << x.a << endl;
   cout << "B::b=" << y.b << endl;
}

int main()
{
   A a;
   B b;
   a.show(a,b);
   return 0;
}