Friend Class in C++ - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

It is possible for one class to be a friend of another class. When this is the case, the friend class and all of its member functions have access to the private members defined within the other class. For example,


#include <iostream> using namespace std; class TwoValues { int a; int b; public: TwoValues(int i, int j) { a = i; b = j; } friend class Min; }; class Min { public: int min(TwoValues x); }; int Min::min(TwoValues x) { return x.a < x.b ? x.a : x.b; } int main() { TwoValues ob(10, 20); Min m; cout << m.min(ob); return 0; }

In this example, class Min has access to the private variables a and b declared within the TwoValues class.


It is critical to understand that when one class is a friend of another, it only has access to names defined within the other class. It does not inherit the other class. Specifically, the members of the first class do not become members of the friend class.


Friend classes are seldom used. They are supported to allow certain special case situations to be handled.




Happy Exploring!

No comments:

Post a Comment