1

Implicit constructor conversion only seems to work with a single conversion.

class A {
public:
    A(std::string s) {}
};
class B {
public:
    B(A a) { }
};

With the above code, running

B b{std::string("Hey")};

works fine.

On the other hand,

B b{"Hey"};

does not.

Does constructor conversion really only work with a single conversion, and why is this the case? To avoid possible ambiguity when different constructors are provided?

Appleshell
  • 7,088
  • 6
  • 47
  • 96

2 Answers2

3

Does constructor conversion really only work with a single conversion?

A single user-defined conversion, yes. It can also involve standard conversions before or after that conversion.

why is this the case?

The simple answer is because that's how the language is specified.

More usefully: if two conversions were allowed, then the compiler would have to consider every type that it knows about, to determine whether there's a suitable intermediate type. Not only would this be a lot of work (with a combinatorial explosion, if you allow any number of conversions), but you're likely to get ambiguities, and subtle changes of behaviour depending on which types happen to be defined at that point in the code.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

B b{"Hey"}; requires conversion to std::string and then conversion to A, and that are two conversions.

Does constructor conversion really only work with a single conversion, and why is this the case?

Yes. That is what the standard requires.

[class.conv]/4 :

At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.

BЈовић
  • 62,405
  • 41
  • 173
  • 273