Ambiguity with constructing objects

Viewed 104

Here is an example I wrote up:

struct Foo
{
  Foo() = default;
  Foo(int)
  {

  };
};

int main()
{
  int baz = 10;
  Foo(1); // OK
  Foo(baz); // Fails, redefinition 
  return 0;
}

Why does Foo(baz) try construct a new object baz, rather than constructing an anonymous object passing an argument baz to the constructor? When I declare an object bar by writing Foo(bar), I get a default initialized object just fine, but once I try passing a argument, it fails. How is the ambiguity resolved?

1 Answers

Foo(baz); is equivalent to Foo baz; which is obviously a declaration.

And as baz was already declared as a local variable of type int earlier in the same scope, you get a redefinition-error.

Related