Question Details

No question body available.

Tags

c++

Answers (1)

Accepted Answer Available
Accepted Answer
November 9, 2025 Score: 6 Rep: 19,491 Quality: Expert Completeness: 80%

The plan is flawed

Your stated desire is to designate a class named bar with internal linkage as a friend. Think about this for a moment. Your source file will declare such a class. So can every other source file. Rather than preventing users of the library from accessing the internals of foo, your proposed strategy (if it was possible) would have the effect of opening up the doors, allowing each and every source file to define a class that is a friend of foo. Everyone would be able to access the internals of foo.

So what can you do? Drop the requirement that bar have internal linkage. Give bar external linkage so that your definition of it (plus the One Definition Rule) blocks all other source files from defining a different version of it. Keep its definition in your source file, but add a forward declaration in the header. There is very little that someone can do with an incomplete type, which is a much better fit to your goal than giving everyone carte blanche to access foo.

My preference for such a declaration would be to make it a nested class. This is simpler in that a separate friend declaration is not necessary. In addition, this fits your "hide stuff" strategy in that a nested class can be private, making it harder to access outside the implementations of foo and its friend, foobaz. (One can get around private if one tries hard enough, though. Access specifiers are not security, so maybe public would be good enough and more convenient for your code.)

Header:

struct foo { private: struct bar; //