Search code examples
c++language-lawyerdeclarationinner-classesdefinition

Defining sub-structure of sub-class inside parent class


Consider the following snippet of code:

class MyClass
{
private:
    struct PrivateClass
    {
        struct SubStruct;
    };

public:
    struct PrivateClass::SubStruct {};

private:
    PrivateClass::SubStruct member;
};

MSVC and gcc compile this code without any errors. clang, however, produces the following error:

<source>:10:26: error: non-friend class member 'SubStruct' cannot have a qualified name
    struct PrivateClass::SubStruct {};

So, who's right? Is this a clang bug?


Solution

  • Standard (latest draft) says:

    [class.nest]

    If class X is defined in a namespace scope, a nested class Y may be declared in class X and later defined in the definition of class X or be later defined in a namespace scope enclosing the definition of class X.

    In this example, the class SubStruct that is declared in the class PrivateClass is defined in neither later in PrivateClass nor later in a namespace scope (but rather, later in a class scope of the outer MyClass). Nor is PrivateClass itself defined in a namespace scope.

    Unless there is another rule allowing this, the definition of the sub-nested class as in the example is not at least explicitly allowed. Clang seems to be correct.