According to https://en.cppreference.com/w/cpp/language/injected-class-name
In a class scope, the name of the current class is treated as if it were a public member name; this is called injected-class-name. The point of declaration of the name is immediately following the opening brace of the class definition.
int X;
struct X {
void f() {
X* p; // OK. X refers to the injected-class-name
::X* q; // Error: name lookup finds a variable name, which hides the struct name
}
};
So what is really happening in the code? Is X* p
turned into X::X* p
?
So what is really happening in the code? Is X* p turned into
X::X*
p?
Basically. The name lookup rules start in the narrowest scope. When you do X* p;
in f
is looks in f
's scope and doesn't find anything. Then it checks X
's scope since f
is scoped to X
. It finds X
since it is injected into the class scope so it stops there and you get the class type.
When you do ::X* q;
then ::X
says look for X
in the global namespace, and there is finds a variable, not a type so you get an error.
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