0

Both vector<int> vec(c, n) and vector<int>(c, n) call same constructor right?

vector<vector<int>> vec(2, vector<int>(2, 3)); // works fine
vector<vector<int>> vec(2, vector<int>v(2, 3)); // error
// error: expected primary-expression before ‘v’

And constructors don't return anything right? vector<int>(c, v) here returned a vector. If vector<int>(c, v) and vector<int>vec(c, n) are not same, then what's vector<int>(c, n) and which constructor is it calling?

One answer described calling constructor without object would create anonymous object and would be destroyed after the immediate ;

TheScore
  • 329
  • 3
  • 14
  • 1
    They both call the same constructor, but first also declares a variable, and can't be used as an expression. – bereal Oct 09 '20 at 05:39
  • 1
    That `v` in the second line makes no sense. Why don't you use a name for the first argument as well then? As in `vector> vec(int i(2), vector v(2, 3));`? That would make just as much sense (but at least be consistent). What `vector> vec(2, vector(2, 3));` is doing is nothing different from calling a function, passing a set of arguments, and you don't declare variables when *calling* a function. – Some programmer dude Oct 09 '20 at 05:44
  • @Someprogrammerdude Yes agreed but I didnot know the difference b/w `vectorvec(c, v)` and `vector(c, v)` and framed a question this way. – TheScore Oct 09 '20 at 05:47
  • @Someprogrammerdude Going through your comment helped me understand most of it but i'm stuck here. `vectorvec(c, v)` here `v` needs to be lvalue or rvalue right? `vector>(2, vector(c, v))` the 2nd arg would call a constructor but constructors don't have return statement. What's happening here? – TheScore Oct 09 '20 at 06:03
  • @CPPnoob In your above comment, by calling its constructor you are creating a temporary instance of the class, which is being copied/moved as an argument to the constructor of the outer vector. That anonymous object thing you have written in the end of your post is correct to an extent. Although destruction after `;` is quite a amateur remark. – brc-dd Oct 09 '20 at 06:32
  • The compiler generates code that creates the object, and then calls its constructor. The constructor doesn't need to return anything, as the object being constructed is `this` (inside the constructor function). Please invest in [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) as they should contain that information (and much more). – Some programmer dude Oct 09 '20 at 07:17

0 Answers0