Friend

What does the “friend” keyword mean in C++ ? Let’s say that it can be useful when we, as developers, need to access private members from outside of a class, which is usually restricted by the compiler. To illustrate, suppose we have two simple classes as shown in the image. In line 3, we set class B as a friend class of class A. This means that all methods of class B will be able to access the private members of class A. Well, you might be wondering about the difference between using "friend" and creating a setter method in class A that allows the "myFunction" method to increment the "d" attribute. While both approaches achieve the same result, using "friend" is more efficient because it eliminates the need for an additional setter method, which could slow down the application. Furthermore, it is possible to designate a specific method as a friend of class A. This approach may be preferable if the only requirement is to access the "d" attribute through the "myFunction" method, rather than granting access to the entire class B. However, it's important to note that using "friend" increases code coupling, so it should only be used when it can significantly improve efficiency, such as when a specific operation is frequently used in our application. What about you? When and why do you use ”friend”?