Reputation: 1054
I'm not sure what search terms I even need to use to find the answer to this question, so sorry if this is duplicated. Basically, Why does this compile?
struct A {
A(){};
A(const char*){};
};
int main() {
//const char* b = "what is going on?";
A(b);
return 0;
}
But this does not?
struct A {
A(){};
A(const char*){};
};
int main() {
const char* b = "what is going on?";
A(b);
return 0;
}
test.cpp: In function ‘int main()’:
test.cpp:8: error: conflicting declaration ‘A b’
test.cpp:7: error: ‘b’ has a previous declaration as ‘const char* b’
What feature of c++ is causing this ambiguity?
The main goal of this is to create an anonymous variable on the stack of type A. Similar to A a(b);
, but not naming a.
Upvotes: 2
Views: 111
Reputation: 16633
This is caused by an ambiguity in the C++ grammar. A(b);
is parsed as a definition of b
, an object of type A
. This exact issue is described in [stmt.ambig].
To fix this, either use uniform initialization A{b};
or surround it with parentheses to force it to be an expression instead of a declaration (A(b));
. Either fix will allow your program to compile.
Upvotes: 5