In C++, a friend function is a special function that can access the private and protected members of a class. Although a friend function is not a member function of the class, it can access all members of the class as if it were a member function.
There are two main purposes for using friend functions:
-
Implementing operator overloading: Sometimes, we need to overload operators (e.g., the
<<operator) for a class, which require access to the class's private data. By declaring these operator functions as friends of the class, they can access the private and protected members. -
Enabling tight cooperation between classes: When two or more classes need to work closely together and access each other's internal states, we can use
friendfunctions or classes to establish this relationship.
Example
Consider a simple class Box with a private member width. We can create a friend function to access this private member.
cpp#include <iostream> class Box { private: double width; public: Box(double wid) : width(wid) {} // friend function friend void printWidth(Box box); }; void printWidth(Box box) { // Access private member from the friend function std::cout << "Width of box: " << box.width << std::endl; } int main() { Box box(10); printWidth(box); return 0; }
In this example, printWidth is a friend function that can access the private member width of the Box class. This would not be possible without the friend keyword, as non-member functions typically cannot access private or protected members of a class.
In summary, the friend keyword provides a flexible way to allow certain external functions or classes to access the internal members of a class while maintaining the principle of encapsulation.