Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of class and variable with the same name

Tags:

c++

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?

like image 299
scdmb Avatar asked May 16 '13 16:05

scdmb


2 Answers

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.

like image 78
user123 Avatar answered Nov 09 '22 01:11

user123


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.

like image 29
David Hammen Avatar answered Nov 09 '22 00:11

David Hammen