2

In C++ when you have an object that is passed to a function by value the copy constructor is invoked. Such as in this function signature:

void foo(Object o);

A couple years ago someone told me that you can pass arguments that fit the constructor of an object that is an argument to a function. So, using the above function signature foo, let's say Object has the constructor:

Object(int a, int b);

we would be able to call the function foo like this:

foo(1,2);

I haven't been able to find any information about this and I think that I either misinterpreted what I heard years ago or that the person was just wrong. Is there any way to do this other than:

foo(Object(1,2));

and if not, is there a reason that this constructor can not be implicitly invoked during a function call?

  • 3
    `foo( { 1, 2 } );` –  Jan 31 '18 at 17:23
  • 3
    ... provided that `Object`'s constructor is not explicit. – Quentin Jan 31 '18 at 17:26
  • C++ does do implicit conversions using single value constructors that are not qualified with the 'explicit' keyword. [This was a helpful read](https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-mean) – Connor Crabtree Jan 31 '18 at 17:40
  • @ConnorCrabtree this also applies to constructors with no or several parameters since C++11 (which brought uniform initialization). – Quentin Jan 31 '18 at 17:59

1 Answers1

4

A couple years ago someone told me that you can pass arguments that fit the constructor of an object that is an argument to a function.

If you recall it right, what was said is wrong.

Given your function and class, you may not use:

f(1, 2);

However, you may use:

f({1, 2});

The {...} will call an appropriate constructor, if one matches.

As a matter of personal preference, I would still use:

f(Object{1, 2});

IMO, the intent is more clearly expressed when using Object{1, 2} than when using just {1, 2}.

R Sahu
  • 204,454
  • 14
  • 159
  • 270