Reputation: 310
There are a number of posts about the C++ friend keyword. I see the advantages of having friend classes. Many concerns are raised and answered regarding whether or not encapsulation is broken by the friend keyword, but all of these responses seem to be directed towards using friend for classes.
But what about friend functions? I can't for the life of me see why you would want this. Once you have any friend function, aren't you allowing any class that ever comes along to access all your private data/functions?
class Foo
{
private:
int neverSetToZero;
public:
Foo() { neverSetToZero = 1; }
friend void Whateveryoudowiththisdonttouchneversettozero(Foo * t);
};
void Whateveryoudowiththisdonttouchneversettozero(Foo * t)
{
(*t).neverSetToZero=0;
}
int main()
{
Foo t;
Whateveryoudowiththisdonttouchneversettozero(&t);
return 0;
}
Upvotes: 1
Views: 847
Reputation: 726839
But what about friend functions? I can't for the life of me see why you would want this.
The common use case for adding a friend
function is to place implementation logic into a function that cannot be a member function, but must be a free-standing function instead.
For example, non-member binary operators and overloads of the <<
operator are commonly made friends of the corresponding classes.
In all cases of a friend
function that I have seen, the code that "friends" a function also supplies the implementation of the same function. There is no use case for leaving an unimplemented friend function in your class. Essentially, the feature lets you build free-standing logic with the knowledge of your class.
Upvotes: 4
Reputation: 171167
I'd say that a friend function is simply an extension of the public interface of the class, which uses a slightly different syntax and allows implicit conversions on all of its parameters (whereas member functions don't do that on their first/implied parameter).
In other words, the author of the class which grants friendship should be the one in control of the friend function. If you just declare a friend function in your class and allow clients to define that function, then certainly hell breaks loose (and program breaks down). But that's not what friend functions are for.
Upvotes: 6