In C++, private and protected members of a class cannot be accessed from outside the class. However, C++ provides a special feature called a Friend Function.
A friend function of a class is defined outside that class's scope, but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.
To declare a function as a friend of a class, use the friend keyword in front of the function prototype inside the class definition.
class MyClass {
private:
int secretData;
public:
friend void revealSecret(MyClass obj); // Friend function declaration
};
Let's look at a practical example where a normal function needs to calculate the distance between two points, requiring access to private coordinates.
#include <iostream> using namespace std;class Box { private: int width;
public: // Constructor to set width Box(int w) { width = w; } // Friend function declaration friend void printWidth(Box b); };
// Friend function definition // Notice we DO NOT use Box::printWidth because it is NOT a member function! void printWidth(Box b) { // Because printWidth is a friend of Box, it can directly access b.width cout << "Width of box is: " << b.width << endl; }
int main() { Box myBox(15);
// Call the friend function directly (no dot operator) printWidth(myBox);
return 0; }
myBox.printWidth()). They are called like regular functions (printWidth(myBox)).Can a friend function access the private members of the class it is friends with?