3

No arguments over good style, I'm just interested here in what is legal in standard c++. This is a small example of something that came up in a much bigger bit of code.

Clang and Visual Studio compile this without error and it appears to work perfectly well. I don't even get a warning from either.

GCC gives the following error and refuses to even compile the code...

test.cpp:1:8: error: changes meaning of 'test' from 'struct test' [-fpermissive]

Is this legal code, or not? I understand what gcc is saying, but is this code actually in error?

struct test
{
    int data;
};


struct app
{
    test test;
};

int main()
{
    app myapp;
    myapp.test.data = 123;
}
jcoder
  • 29,554
  • 19
  • 87
  • 130

1 Answers1

1

It's invalid, because the variable and the type are in different scopes.

Hiding kicks in only when they're in the same scope:

[C++14: 3.3.10/2]: A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.

Clang and Visual Studio are wrong.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • **−1** The cited paragraph is about something else entirely, namely the names co-existing. It was C's kind of namespaces, resolved by using the `struct` keyword. – Cheers and hth. - Alf Jul 15 '16 at 10:33
  • @Cheersandhth.-Alf: What? Did you even read the answer? That this paragraph allows only for hiding when the names co-exist is literally the point. – Lightness Races in Orbit Jul 15 '16 at 10:34
  • (I could quote the entire remainder of the standard to prove that there's no rule to allow it for the OP's case, but there's a maximum size limit on SO answers) – Lightness Races in Orbit Jul 15 '16 at 10:35
  • The paragraph you cite is about reusing a name in the same scope as where it's used for a class name or enumeration. This was allowed by early C (and later C and now C++) because you would use `struct` or `enum` keywords where you needed to refer to the type. It's not an issue at all when the class or enumeration is declared in an enclosing scope. Then it's just normal name hiding. – Cheers and hth. - Alf Jul 15 '16 at 10:39
  • I'd better add that the dupe shows that the conclusion above, before the first comma, is correct: it's invalid. But not for the cited reason – Cheers and hth. - Alf Jul 15 '16 at 10:56