I was reading about one of the strange C++ feature called Injected class name here.
I tried following simple program
#include <iostream>
class test
{
int s{3};
public:
int get_s()
{ return s; }
};
int main() {
class test::test s; // struct test::test s; also allowed. Why???
std::cout<<s.get_s();
}
If I replace class keyword with struct in first line of main() program still compiles & runs fine. See live demo here. Why? Shouldn't I get compiler error? Why it compiles fine?
I believe the relevant verse is in 7.1.6.3/3 (highlighting mine, quoted here from a draft of the C++17 Standard):
Thus, in any elaborated-type-specifier, the
enum
keyword shall be used to refer to an enumeration (7.2), theunion
class-key shall be used to refer to a union (Clause 9), and either theclass
orstruct
class-key shall be used to refer to a class (Clause 9) declared using theclass
orstruct
class-key.
So either keyword can be used to stipulate the scope within which the injected class name exists, irrespective of which was used to declare/define test
.