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

212 Views Asked by At

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?

2

There are 2 best solutions below

8
On BEST ANSWER

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.

0
On

This qualified name ::X is searched in the global namespace. As there is no type with such a name (the variable declaration hides the type struct X) the compiler issues an error.

You could use an elaborated name like

int X;
struct X {
    void f() {
        X* p; // OK. X refers to the injected-class-name
        struct ::X* q; // OK. elaborated name struct ::X
    }
};