Reputation: 45
Just wondering ...
Playing around with C++, I found that if you create a class called circle
, and then declare a variable named exactly as the name of the class, the compiler does not complain. For example:
class circle {
// whatever it does in here
};
circle circle; // is a valid statement, but
circle *circle = new circle(); // gives you a 'circle' is not a type complain
It turns out that this goes for string string = "string"; as well. And tried it with Java, possible also. I guess it might work on C# too, but I haven't tried.
Can anyone tell me the reason behind this and whether this is an intentional feature?
Upvotes: 3
Views: 233
Reputation: 545865
The reason has got nothing to do with dynamic allocation. Rather, it’s illustrated by this code:
// declaration | initialisation
// ---------------+---------------
circle *circle = new circle();
// ^
At the point marked ^
, the declaration is complete and circle
is known in the current scope as a variable. So you are trying to do new variablename()
which doesn’t work.
Upvotes: 1
Reputation: 55897
n3337 9.1/2
A class declaration introduces the class name into the scope where it is declared and hides any class, variable, function, or other declaration of that name in an enclosing scope (3.3). If a class name is declared in a scope where a variable, function, or enumerator of the same name is also declared, then when both declarations are in scope, the class can be referred to only using an elaborated-type-specifier (3.4.4).
n3337 9.1/4
[ Note: The declaration of a class name takes effect immediately after the identifier is seen in the class definition or elaborated-type-specifier. For example, class A * A; first specifies A to be the name of a class and then redefines it as the name of a pointer to an object of that class. This means that the elaborated form class A must be used to refer to the class. Such artistry with names can be confusing and is best avoided. —end note ]
So.
class circle {
// whatever it does in here
};
int main()
{
circle *circle; // gives you a 'circle' is not a type complain
}
compiles well.
class circle {
// whatever it does in here
};
int main()
{
circle *circle = new class circle(); // gives you a 'circle' is not a type complain
}
compiles well too.
Upvotes: 2