Question

This similar ill-fated question got comments and short answers, before it was closed, to the effect: Because that's how the language is defined. Here I am asking for the evidence within the C++ Standard that it is so defined.

gcc 4.8.1 and clang 3.3 alike, with default diagnostic options or stricter, give errors for extra qualification or explicit qualification on code such as:

struct x
{
    int x::i; // Error: gcc/clang: "extra"
};

int ::y; // Error: gcc: "explicit", clang: "extra"

gcc has diagnosed such errors since v4.1. But popular compilers are not unanimous about these errors. MSVC++ 2012 (Nov CTP) gives an error at int ::y; but even with /Wall, gives no diagnostic at all int x::i; - the kind of case that the ill-fated questioner was raising - and that difference suggests deliberation by the MS compiler writers.

How are these errors warranted by the Standard, if they are? References to the C++11 Standard will suffice.

An answer might be "They follow from grammar". In that case, please try to show how they follow from the grammar and feel free to use the Standard's grammatical classifications. I have a copy and will re-read it to understand the explanation.

Was it helpful?

Solution

A qualified name in C++ always must refer to a previously declared name. This is specified in clause 8.3 and 3.4.3.2.

You cannot firstly declare a variable or member by using a qualified name - it will end up in a "cannot resolve identifier"-liky compiler error. Such qualifiers are designed to be used for redeclaration. Hence the requirement that these names must find previously declared entities.

OTHER TIPS

It is a bug in the Microsoft compiler to allow x::i within the definition of struct x. There are several of these errors in the MSVC front end, and have been reported to Microsoft but they get closed without being fixed (see similar but different error reported here: https://connect.microsoft.com/VisualStudio/feedback/details/783433/c-compiler-accepts-explicit-constructor-call#details and https://connect.microsoft.com/VisualStudio/feedback/details/794504/keyword-struct-before-constructor-name).

The reason it is invalid is because you are both trying to declare a variable int i and provide a scope using x::i. The scope of the variable is dictated by where it is declared, so trying to declare something with a scope specification is trying to declare it somewhere else, which is invalid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top