class A
{
private:
int a;
public:
class B
{
public:
B(int a) : b(a) {}
int b;
};
};
int main(void)
{
return 0;
}
clang (-Weverything) warns:
t.cpp(10,15): warning: constructor parameter 'a' shadows the field 'a' of 'A' [-Wshadow-field-in-constructor]
10 | B(int a) : b(a)
| ^
t.cpp(4,9): note: previous declaration is here
4 | int a;
I know that since C++11 nested classes have access to outer classes as if they were friends, but B
is just declared inside A
(there is no member object of B
in A
, how can B
constructor param a
shadow A
member a
?
Best Answer
Yes.
Namelookup needs no
A
instance inB
. BecauseB
is nested insideA
unqualified name lookup findsA::a
.From cppreference:
c) means that an unqualified unshadowed
a
insideB
refers toA::a
. Your code works becauseint a
shadowsA::a
and because in the initializer listb(a)
uses the constructor parameter calleda
.That the enclosing class is a friend does not matter at this point, because access comes after namelookup. As Jarod42 pointed out, you can modify the code (rename the parameter but keep
b(a)
) to get an error becauseA::a
is non static.