C++ lets you grant functions the same privileges of member functions by declaring them "friends" of a class (or struct). What are friends for? They let the implementor of the class write non-member functions without exposing the implementation to all callers. friends are a Good Thing: they enhance modularity.

Obviously, the conscientious programmer will want to keep as few friends as let her code her class' API. In some (good!) designs, some friends exist only as part of the implementation of some larger feature. The natural approach is to declare such functions, which should only be seen inside one filetranslation unit, as static.

You can't declare a static friend.

The design will thus be flawed.

As usual, there are excellent reasons for this: It's not just a misfeature or a wart; the entire language is so hideously contorted that allowing static friends would be even more dangerous than not allowing them.

Recall that a class declaration is usually situated in a header file (it will always be there in situations where modularity is a problem). The header file is #included everywhere in the code. And friends are declared in the header file. So every single file using the class knows about its friends.

Suppose you had a static friend. I could define, in some other file than that where you define your friend, another function with the same name and signature. Your header file would declare my function its friend, too! Merely by knowing that a function is a static friend, I could achieve unlimited access to its internals! By attempting to adjust the language to allow us a bit more modularity, we'd destroy all opportunities for hiding. And you cannot put your class' friends in some anonymous namespace: exactly the same problem would apply, as there is no special way of identifying the particular function in an anonymously-namespace with which your class really wants to be friends.

Allowing only extern friends solves this: You can only link one extern function with a given name and signature. So, having declared and defined your friends, any compiled and linked program will be guaranteed free of this subversion.

Of course, if your OS lets you use dynamic libraries (DLLs) in some way, you can probably overcome this limitation at run-time. But such perversions are outside the scope of ISO C++...

Log in or register to write something here or to contact authors.