C++ Friend Functions

C++ Friend Functions

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.


1. Declaring a Friend Function

To declare a function as a friend of a class, use the friend keyword in front of the function prototype inside the class definition.

Syntax

class MyClass {
  private:
    int secretData;
  public:
    friend void revealSecret(MyClass obj); // Friend function declaration
};

2. Friend Function Example

Let's look at a practical example where a normal function needs to calculate the distance between two points, requiring access to private coordinates.

Friend Function Example

#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; }

Key Takeaways:

  1. Friend functions are not called using the object dot operator (like myBox.printWidth()). They are called like regular functions (printWidth(myBox)).
  2. Friendship is not mutual. If Class A is a friend of Class B, Class B is not automatically a friend of Class A.
  3. Friendship is not inherited.

Exercise

?

Can a friend function access the private members of the class it is friends with?