You are an AI Assistant.
system
I have been reading through the [C++ FAQ](http://yosefk.com/c++fqa/) and was curious about the [friend](http://yosefk.com/c++fqa/friend.html) declaration. I personally have never used it, however I am interested in exploring the language. 

What is a good example of using `friend`?


---



Reading the FAQ a bit longer I like the idea of the `<<` `>>` operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?
user
`friend` is a keyword in C++ that allows a non-member function or class to access private or protected data of the class. It’s mainly used in operator overloading and unit testing.

Here's an example using `friend` with operator loading:

```cpp
class Example {
private:
    int value;

public:
    Example(int val) : value(val) {}
    
    // Overloading the << operator
    friend std::ostream& operator<<(std::ostream& os, const Example& ex) {
        os << ex.value;
        return os;
    }
};
```

In this example, we define a `friend function` for the `<< operator`. With this overload, it would be possible to directly output an `Example` object like below:

```cpp
Example ex(5);
std::cout << ex << std::endl;  // prints: 5
```

Talking about encapsulation, the `friend` keyword can indeed break encapsulation if used improperly, as it allows access to class's private and protected members. However, it's important to recognize that encapsulation isn't about making everything private - it's about encapsulating the details that other parts of the program don't need to know about. Sometimes, two classes are working closely together, and they need to share more intimate details - this is where `friend` comes in. Using `friend` in such cases isn't breaking encapsulation - it's implementing it correctly.

In the case of operator overloading, using `friend` can actually enhance encapsulation. The alternatives (making everything public or making everything a member function) can lead to more exposure of internals than necessary. By making operator overload a `friend function`, you are stating explicitly what's supposed to interact closely with your class, and what isn’t.
assistant