Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguity with constructing objects [duplicate]

Tags:

c++

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?

like image 878
Krystian S Avatar asked Nov 04 '18 22:11

Krystian S


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.

like image 109
Deduplicator Avatar answered Sep 29 '22 22:09

Deduplicator