Search code examples
c++friend

C++ Friend Functions Improve Encapsulation?


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

Solution

  • 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.