It is valid to hide the name of a class with a variable in fact if you look at the C++draft standard section 3.3.10
Name hiding paragraph 2 says(emphasis mine):
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.
I don't think it is good practice and it would lead to hard to maintain code. This line of code is actually declaring a function:
a a1();
you can alternatively use this pre-C++11:
a a1 ;
or uniform initialization introduced in C++11 :
a a1{} ;
Circling back to name hiding, I was pleasantly surprised to see that clang
will warn you about this with this code regardless of the warning levels set:
int main()
{
a a;
a a2 ;
}
I receive this message:
main.cpp:12:10: note: class 'a' is hidden by a non-type declaration of 'a' here
a a;
^
although I can't see to obtain a similar warning from gcc
.
Update
Thinking about this comments I made earlier on warts of uniform initialization, I realized that had you suspected that a1
was somehow not the correct type you could have have used typeid to debug what was going on. For example this code:
std::cout << typeid(a).name() << std::endl ;
std::cout << typeid(a1).name() << std::endl ;
results in this output on Coliru live example:
1a
F1avE
and passing it through c++filt you receive this output:
a () // A function that returns type a
a // type a
a1
isn't an object, but a function. – Freewaymost-vexing-parse
tag when it was determined to not be relevant? – Shearwaterstruct
andclass
just as you could in C to make it less confusing.class a a;
reads better thana a;
. I ran into this in real life with a class namedurl
and a variable namedurl
. So it wasclass url url;
– PassionalX f()
is a function declaration, just asint f()
is. It may well be similar in appearance, but it's not the same thing at all. "another manifestation of the rule" is not the same as "equally obscure and confusing and deserving of a derogatory name". – Beaufort