Friend functions and friend classes allow a class interface to be extended in a natural and efficient way. For some problems, friend functions lead to more intuitive code, while friend classes are needed when two classes are tightly coupled. Non-member friend functions are especially useful for implementing operator overloading, a good example being operator<<.
Friend functions do not break encapsulation, but rather enhance a class interface. Although this is the case, friends should be used judiciously; a member function will often do just as well. As a general rule of thumb, use member functions where possible, and friends where necessary. A well-designed project will not be free of friend functions, but will instead use them in places where non-members are naturally part of a class.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |