Sanish
Sanish

Reputation: 1729

C++ friend functions/class uses?

What is the real use of a friend function/class in C++? Could you give an example where only friend is the right approach?

Thanks

Upvotes: 1

Views: 1351

Answers (3)

Yola
Yola

Reputation: 19031

i think often friend function usage its a matter of readability. For example next overloaded operator looks symmetrically and this may be good for code reader.

friend const X operator+(const X&, const X&);

inline const X operator+(const X& arg1, const X& arg2)
{
    X r;
    r.x = arg1.x + arg2.x;
    return r;
}

But main point its their ability to access private data of two different classes.

Upvotes: 0

juliomalegria
juliomalegria

Reputation: 24921

Using friend is actually very discouraged in C++ (it kinda breaks the whole encapsulation idea), but it comes to my mind an example where only friend is the right approach:

friend ostream & operator<< (ostream & out, const MyClass & C);
friend istream & operator>> (istream & in, MyClass & C);

Upvotes: -2

Charlie Martin
Charlie Martin

Reputation: 112386

"In C++, only your friends can access your private parts."

The point of a friend is that you can package your software into smaller groupings, like friend classes etc, while still allowing access to the internals of a class. This arguably lets you maintain finer control on encapsulation than without friending.

Upvotes: 8

Related Questions