The friend function f
doesn't have access to a private member of the enclosing class A
.
#include <iostream>
class A{
const static int p = 1;
class B {
friend void f() {
std::cout << p << '\n';
std::cout << q << '\n';
}
};
public:
const static int q = 2;
};
void f();
int main()
{
f();
}
At least, this is what I think [class.nest]/4 in N4140 is saying (see below).
§9.7/4
Like a member function, a friend function (11.3) defined within a nested class is in the lexical scope of that class; it obeys the same rules for name binding as a static member function of that class (9.4), but it has no special access rights to members of an enclosing class.
live example
I believe that you are correct, in that both Visual Studio and GCC correctly reject the code based on the spec you cited. Clang appears to be in error by allowing access to A
's private member variable p
from the friend function f()
, because f()
is a friend of B
, not A
.
For a good discussion of the scope of friend functions, see the top-voted answer in the following SO post: What's the scope of inline friend functions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With