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?

3
  • 1
    To avoid the halting problem on compilation, likely :) Commented Sep 19, 2013 at 13:19
  • 1
    "Does constructor conversion really only work with a single conversion?" Yes Commented Sep 19, 2013 at 13:19
  • You get one implicit user-defined conversion, not more. Commented Sep 19, 2013 at 13:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.