There is this code:
int x;
//void x(); // error: redefinition of 'x' as different kind of symbol
class x {}; // works ok
int main() {
return 0;
}
Why is it legal to define variable and class with the same name but it is not legal to define variable and function with the same name?
First Case: 2 Identifiers
int x;
void x();
Second Case: 1 Identifier, 1 Typename
int x;
class x {};
The compiler can't handle the first case because you have 2 identifiers with the same name, so there could be an ambiguity. (Example: Try getting the memory address of one of them. That's one case where an ambiguity could arise)
The compiler can handle the second case because one is a type and the other is an identifier, and because it knows where to expect a type and where to expect an identifier, there is no ambiguity.
What's going on here is specific to C++. The use of x
as a class name is hidden.
Section 3.3.7 (Name Hiding) paragraph 2:
A class name (9.1) or enumeration name (7.2) can be hidden by the name of an object, function, or enumerator declared in the same scope. If a class or enumeration name and an object, 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 object, function, or enumerator name is visible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With