C++ Friend Functions

In C++, a friend function is a non-member function that has access to private and protected members of a class. Friend functions are declared using the `friend` keyword inside the class.

1. Friend Function Syntax

A friend function is declared inside the class but defined outside.

C++
Syntax of friend function
class ClassName {
    friend return_type function_name(parameters);
    private:
        int data;
};

return_type function_name(parameters) {
    // function body accessing ClassName private members
}

2. Friend Function Example

This example demonstrates a friend function accessing private members of a class.

C++
Example: Friend function
#include <iostream>
using namespace std;

class Box {
private:
    int width;
public:
    Box(int w) : width(w) {}
    friend void printWidth(Box b); // friend function declaration
};

void printWidth(Box b) {
    cout << "Width of box: " << b.width << endl;
}

int main() {
    Box box(10);
    printWidth(box); // friend function can access private member
    return 0;
}

3. Key Points

1. Friend functions are not members of the class. 2. They can access private and protected members of the class. 3. Declared using `friend` keyword inside the class. 4. Useful for operator overloading and functions needing access to multiple class internals.

4. Common Mistakes

1. Forgetting to declare the function as friend inside the class. 2. Assuming friend functions are member functions; they are not. 3. Overusing friend functions can break encapsulation; use sparingly.

Conclusion

C++ friend functions allow non-member functions to access private and protected members of a class. They are useful for specific scenarios but should be used carefully to maintain class encapsulation.