I happen to write a code like this:
class a
{
public:
a() {}
};
int main()
{
a *a = new a; // line 10
a a; // line 11
return 0;
}
g++ errors out:
2.c: In function ‘int main()’:
2.c:10:16: error: expected type-specifier before ‘a’
2.c:10:16: error: cannot convert ‘int*’ to ‘a*’ in initialization
2.c:10:16: error: expected ‘,’ or ‘;’ before ‘a’
2.c:11:7: error: expected ‘;’ before ‘a’
I found that, if I change “a *a” to “a *b” at line 10, then g++ is happy, here is the good code:
class a
{
public:
a() {}
};
int main()
{
a *b = new a;
a a;
return 0;
}
I am confused, not sure why the original code does not compile and how the “fix” works.
Any idea?
See Vaughn’s answer for details. However, you can fix this problem if you specify that you want to use the class and not the variable:
or
Explanation
Back in the days of C structs were put in their own namespace. In C++ something similar happens, however, the class names are available outside of their namespace, as long as there is no local function or variable with the same name.
If you happen to use the same name for both a class/struct
Aand a variable/functionAyou have to use thestruct/classkeyword, because the compiler interprets all following occurrences ofAas the variable/function and not the struct/class.