-1

I have a question about a compiler/language behaviour that I expected to behave differently. Why does the following code compile?

#include <vector>
class A { }; 
int main() {
    A a(std::vector<int>()); 
}

It does not compile with std::vector<int>(0) or other values. It does however compile if you give std::vector<int>(*) a pointer. It also works with other types than "int". I expected the code to not work at all. Can someone explain to me what's happening?

Here is a code snipped on cpp.sh for reference: http://cpp.sh/4l3a

I use gcc version 4.8.4.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Squolly
  • 96
  • 3

1 Answers1

2

I assume you expected it to fail compilation because A has no constructor taking a vector.

A a(std::vector<int>());

This is not a declaration of an A, though. It's a declaration of a function called a, taking a pointer (with no name) to a function returning std::vector<int>, and returning A.

When you changed it to this:

A a(std::vector<int>(0));

the use of an integer literal forces the parser to recognise this as an object instantiation instead, which of course fails because A has no constructor taking a vector.

You can force the parser's recognition in your first case, too, using an extra set of parentheses:

A a((std::vector<int>()));

This is an instance of the most vexing parse.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • You are right. I supposed it shouldn't work because there is no constructor defined in A for std::vector. Thank you very much for your answer. It helped me a lot! And I learned something new about the language. Couldn't find anything by searching a I didn't know what to search for. – Squolly Oct 16 '15 at 15:39
  • @Angew: thanks for clarifying this – Squolly Oct 16 '15 at 15:44