Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when Injected-Class-Name occurs? (C++)

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?

like image 275
csguy Avatar asked Dec 22 '22 19:12

csguy


1 Answers

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.

like image 137
NathanOliver Avatar answered Dec 26 '22 00:12

NathanOliver