jamesdlin jamesdlin - 4 months ago 25
C++ Question

What's actually going on in this AnonymousClass(variable) declaration?

Trying to compile:

class AnonymousClass
AnonymousClass(int x)

int main()
int x;
return 0;

generates errors from MSVC:

foo.cpp(13) : error C2371: 'x' : redefinition; different basic types
foo.cpp(12) : see declaration of 'x'
foo.cpp(13) : error C2512: 'AnonymousClass' : no appropriate default constructor available

g++'s error messages are similar:

foo.cpp: In function ‘int main()’:
foo.cpp:13: error: conflicting declaration ‘AnonymousClass x’
foo.cpp:12: error: ‘x’ has a previous declaration as ‘int x’
foo.cpp:12: warning: unused variable ‘x’

It's easily fixable by giving the
object an explicit name, but what's going on here and why? I presume that this is more declaration syntax weirdness (like the cases described in Q10.2 and Q10.21 of the comp.lang.C++ FAQ), but I'm not familiar with this one.


It defines a variable x of type AnonymousClass. That is why you're getting redefinition error, because x is already declared as int.

The parentheses are superfluous. You can add even more braces like:

//and so on

All of them are same as:

AnonymousClass x;

Demo: http://www.ideone.com/QnRKH

You can use the syntax A(x) to create anonymous object, especially when calling a function:

int x = 10;
f(A(x));        //1 - () is needed
f(A((((x)))));  //2 - extra () are superfluous

Both line 1 and 2 call a function f passing an object of type A :

But again, the extra parentheses are still superfluous at line 2.