Why can’t I assign to a constructor, when I can assign to a function that “looks” like a constructor?
Example:
struct Bar {
Bar() : b_(false) {}
Bar(bool b) : b_(b) {}
};
struct Foo {
Foo(Bar const & bar) : bar_(bar) {}
Foo operator=(Foo const & f) { return Foo(f.bar_); }
const Bar & bar_;
}
Foo bool_to_foo(bool b) { return Foo(Bar(b)); }
Foo MakeFoo(Bar const & bar) { return Foo(bar); }
Why does this work:
Bar bar;
MakeFoo(bar) = bool_to_foo(true);
when this doesn’t work?
Bar bar;
Foo(bar) = bool_to_foo(true); // Error: 'bar': redefinition; different basic types
MakeFoo(.) and Foo(.) have the same signature, and the same function.
What’s special about the constructor?
This line:
does not do what you think it does. It does not declare a temporary object initialized with
bar.What it actually does is to declare an object named
barof typeFooand initialize it with the valuebool_to_foo(true).In that sense, it is exactly equivalent to:
Since you already have an object named
barin scope, this is a redefinition.If you still want to do what you are trying to do, you might try:
But, since that is both ugly and confusing, I won’t describe it further.