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?
Basically. The name lookup rules start in the narrowest scope. When you do
X* p;infis looks inf's scope and doesn't find anything. Then it checksX's scope sincefis scoped toX. It findsXsince it is injected into the class scope so it stops there and you get the class type.When you do
::X* q;then::Xsays look forXin the global namespace, and there is finds a variable, not a type so you get an error.