Example of a friend Function


/************************************************************************
*

In the following example, the friend function print is a member of class Y and accesses the private data members a and b of class X .

                                                                        *
************************************************************************/


// This example illustrates a friend function.

#include <iostream.h>
class X;
class Y
{
public:
      void print(X& x);
};
class X
{
public:
      X() {a=1; b=2;}
private:
      int a, b;
      friend void Y::print(X& x);
};
void Y::print(X& x)
{
      cout << "A is "<< x.a << endl;
      cout << "B is " << x.b << endl;
}
void main ()
{
      X xobj;
      Y yobj;
      yobj.print(xobj);
}


/************************************************************************
*

In the following example, the friend class F has a member function print that accesses the private data members a and b of class X and performs the same task as the friend function print in the above example. Any other members declared in class F also have access to all members of class X. In the example, the friend class F has not been previously declared, so an elaborated type specifier and a qualified type specifier are used to specify the class name.

                                                                        *
************************************************************************/


// This example illustrates a friend class.

#include <iostream.h>
class X
{
public:

      X() {a=1; b=2;}           // constructor
private:
      int a, b;
      friend class F;           // friend class
};
class F
{
public:
      void print(X& x)
      {
            cout << "A is " << x.a << endl;
            cout << "B is " << x.b << endl;
      }
};
void main ()
{
      X xobj;
      F fobj;
      fobj.print(xobj);
}


/************************************************************************
*

Both the above examples produce the following output:

A is 1
B is 2


                                                                        *
************************************************************************/