Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to specify a duplicate C++ class scope? [duplicate]

Tags:

c++

g++

Possible Duplicate:
Why are redundant scope qualifications supported by the compiler, and is it legal?

I wouldn't expect this to compile but it does. Could this be a compiler bug, or does it have some correct meaning?

$ g++ -c scopes.cpp
$ cat scopes.cpp
class Log {
public:
    Log() { }
    static void fn() { }
};

void test() {
    Log::Log::Log::Log::Log::Log::fn();
}

$ g++ --version
g++ (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3
like image 664
Howard Rubin Avatar asked Oct 11 '12 16:10

Howard Rubin


1 Answers

Yes, it's legal. A class's name is inserted into its own namespace, which is called the injected-class-name. From C++03 §9/2:

[...] The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name. For purposes of access checking, the injected-class-name is treated as if it were a public member name.

Note that Log::Log names the class constructor, which is only allowed in certain contexts, but as long as you end the chain of Log::Log::... with something other than Log (such as fn), then it doesn't name the constructor. Specifically, §3.4.3.1/1a says:

If the nested-name-specifier nominates a class C, and the name specified after the nested-name-specifier, when looked up in C, is the injected-class-name of C (clause 9), the name is instead considered to name the constructor of class C. Such a constructor name shall be used only in the declarator-id of a constructor definition that appears outside of the class definition.

like image 61
Adam Rosenfield Avatar answered Sep 20 '22 07:09

Adam Rosenfield