Give an example of friend classes in C++ and an example of when you would use one.
In C++, the friend keyword can be applied to either a function or a class. A friend function or friend class has access to the private members of the class in which the declaration occurs. There are programmers who think that this feature violates the principles of object oriented programming because it allows a class to operate on another class’s private members. And, this can lead to unexpected bugs when the internal implementation of a class causes problems with the friend class that accesses it.
C++ Friend Classes Protected
In addition to having access to private members, you should remember that friend classes (and functions) will also have access to any protected members of the class as well.
What are the benefits of a friend class?
There are some scenarios in which it would be very beneficial to use a friend class. For example, suppose that we have implemented a linked list array class. And, let’s suppose that we also want to create a separate class to iterate through the linked list. The iterator class would most likely need to have access to the linked list class’s private members in order to function correctly. In this scenario, it would make a lot of sense to declare the iterator as a friend to the linked list class. The two classes essentially depend on each other, so having them be separated does not make much sense.
What about Friend Classes in Java and C#?
Although both Java and C# do not support the concept of friend classes, they do have something called nested classes. Nested classes have access to their enclosing class’s private methods and data. So, nested classes provide almost the same functionality that friend classes do, and are a good alternative in Java and C#.