What is Friend Function in C++: Explanation and Example
friend function in C++ is a special function that can access private and protected members of a class, even though it is not a member of that class. It is declared inside the class with the keyword friend and helps when external functions need direct access to class internals.How It Works
Imagine a class as a locked box that keeps its data private. Normally, only the box's own methods can open it and see inside. A friend function is like a trusted friend who has a special key to open the box, even though they don't live inside it.
This function is not part of the class, but the class allows it to access its private and protected data. This is useful when you want an external function to work closely with the class without making the data public to everyone.
Example
This example shows a friend function accessing private data of a class.
#include <iostream> class Box { private: int width; public: Box(int w) : width(w) {} friend void printWidth(Box& b); // Declare friend function }; void printWidth(Box& b) { // Access private member width directly std::cout << "Width of box: " << b.width << std::endl; } int main() { Box box(10); printWidth(box); // Call friend function return 0; }
When to Use
Use a friend function when you need an external function to access private or protected members of a class without making those members public. This is common when two or more classes or functions need to work closely together, like operator overloading or utility functions.
For example, if you want to print or compare objects and need access to their private data, friend functions let you do this cleanly without exposing sensitive details to all code.
Key Points
- A friend function is not a member of the class but can access its private and protected members.
- Declared inside the class with the
friendkeyword. - Helps maintain encapsulation while allowing specific external access.
- Commonly used for operator overloading and utility functions.