5

Possible Duplicate:
Most vexing parse: why doesn't A a(()); work?

I am having this simple C++ issue that is making me wanna restart my CS degree all over again trying to learn something this time. ;)

Why this code doesn't compile:

vector<int> v(int());
v.push_back(1);

while this other one compiles without a single warning

vector<int> v((int()));
v.push_back(1);

It's even hard to find a difference at all (extra parenthesis were added :P).

Community
  • 1
  • 1
  • 3
    If you expect a CS degree to make you fluent in the intricacies of C++, then I think you have the wrong expectations. Silly nonsense like this can always be figured out later (such as on SO), but what good is that if you don't know how to design a tree? – Kerrek SB Jan 24 '12 at 13:41
  • See: http://stackoverflow.com/questions/tagged/most-vexing-parse - should probably be closed as a duplicate ? – Paul R Jan 24 '12 at 13:42

2 Answers2

9

It's called the most vexing parse.

vector<int> v(int());

Declares a function v that takes a function (taking no parameters returning an int) and returns a vector<int>. This is automatically "adjusted" to a function v that takes a pointer to a function (taking no parameters returning an int) and returns a vector<int>.

The extra pair of parentheses inhibits this interpretation as you can't place extra parentheses around parameter declarators in function declarations so (int()) can only be interpreted as an initializer for an object named v.

C++ has an explicit disambiguation rule that prefers to parse things (in this case int()) as declarators rather than expressions if it makes syntactic (but not necessarily semantic) sense.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
1

Indeed its a function declaration. See: http://www.gotw.ca/gotw/075.htm

KasF
  • 212
  • 1
  • 6