In C++ like the friend function, we have friend classes also. By using the keyword “friend” it is possible to make the class a friend to another class. If we make the class a friend class, the member functions that are available in the class will become friends to another class.
Below is the syntax of the friend class. Here is one condition that the friend becoming class must be first declared or defined
1 2 3 4 5 6 7 8 9 10 11 |
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.
Below is the small example that can help us to understand the friend classes usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
/* 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 friend classes:
There may be some situations we want to iterate the linked list through a separate class. In this situation, we need to access the private data member of the list class. At this time, we need to make the class that needs to access the private data of the class list be friend to the list class.