Tuesday, 11 November 2014

Friend classes in C++ with the examples

Friend classes in C++ with the examples:

In C++ like friend function we have the friend classes also. By using the keyword “friend” it is possible to make the class as friend to another class. If we make the class as friend class, the member functions that are available in the class will becomes the friends to the another class.
The below is the syntax of the friend class. Here is one condition that  the friend becoming class must be first declared or defined

class ClsSecond;  // forward declaration:This is the condition

class ClsFirst {

   friend class ClsSecond;      // class ClsSecond is a friend class

}

class ClsSecond {

}


In the above code sample, all member functions of class ClsSecond will be friend function of class ClsFirst. So we can access any member function of the ClsSecond can access the private and protected data of class ClsFirst.

If ClsSecond is declared friend class of ClsFirst then, all member functions of class ClsSecond can access private data and protected data of class ClsFirst but, member functions of class ClsFirst cannot private and protected data of class ClsSecond.

In addition to this, we are having the access to private members, friend classes will also have access to any protected members of the class.

The below is the small example that can help us to understand the friend classes usage:
/* friend classes with the example  */

#include <iostream>

using namespace std;

class ClsSecond; // Farward declaration

class ClsFirst

{

 friend class ClsSecond;   

 public:

  ClsFirst() : iPrivateVal(0)

    { }

  void Dump (const char* pcchTemp)

  {

  cout << pcchTemp << "updating" <<  "\t" << iPrivateVal << endl;

  }

 private:

  int iPrivateVal;

};

class ClsSecond

{

 public:

  void Update (ClsFirst& ocFirst, int iVal )

  {

   ocFirst.iPrivateVal = iVal;

  }

};

int _tmain (int argc, _TCHAR* argv[])

{

 ClsFirst ocFirst;

 ClsSecond ocSecond;

 ocFirst.Dump ("Before");

 ocSecond.Update (ocFirst, 5);

 ocFirst.Dump ("After");

  getchar ();

  return 0;

}


We declared ClsSecond as a friend of ClsFirst so that ClsSecond member functions could have access to the private member, ocFirst.iPrivateVal

In our example, ClsSecond is considered as a friend class by ClsFirst but ClsSecond does not consider ClsFirst to be a friend, so ClsSecond can access the private members of ClsFirst but not the other way around.

The benefits of a friend classes:

There may be some situations we want to iterate the linked list through the separate class. At this situation, we need to access the private data member of the list class. In this time, we need to make the class that which needs to access the private data of the class list to be friend to the list class.

No comments: