Question

Is the following code valid?

struct A 
{
    struct nested;
};

struct B : public A {};

struct B::nested {};

gcc accepts it, but clang rejects it with the following error:

test.cpp:8:14: error: no struct named 'nested' in 'B'
    class B::nested {};
          ~~~^
Was it helpful?

Solution

Yup, it's invalid. Here's the quote.

Section 9 paragraph 11, emphasis mine:

If a class-head-name contains a nested-name-specifier, the class-specifier shall refer to a class that was previously declared directly in the class or namespace to which the nested-name-specifier refers, or in an element of the inline namespace set (7.3.1) of that namespace (i.e., not merely inherited or introduced by a using-declaration), and the class-specifier shall appear in a namespace enclosing the previous declaration. In such cases, the nested-name-specifier of the class-head-name of the definition shall not begin with a decltype-specifier.

In your example, the class-head-name is the tokens B::nested, which comprises the nested-name-specifier B:: and the class-name nested. The class-specifier is the entire struct B::nested { ... }.

OTHER TIPS

B has no nested class named nested. only A has a nested class named nested class A::nested { }; should work just fine

You inherit from A so you don't encapsulated nested struct in B.

From created struct of type B you can only reach struct named nested as it is part of struct B, however to construct struct named nested is responsible A, because it encapsulated nested.

All-in-all your code is invalid.

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