If a class has a single argument constructor my understanding is it is implicitly convertible by the constructor to the type of the argument in appropriate contexts. Defining a conversion operator also makes a class convertible to another type. Questions
- Does the conversion operator ever get called implicitly?
- If both a single argument constructor and conversion operator with the same type are defined for a class does one have precedence over the other or is it ambiguous?
- If you’ve decided that you want a class to be convertible to a given type, which approach is better or should you provide both?
Edit:
I see I didn’t understand clearly the directionality and that the two perform conversions in the opposite directions. As a follow on
- If you have control over two classes that you want to make convertible to and from each other is there a preferred way in terms of these two operations to accomplish this?
- Is it possible mark the conversion operator as explicit?
No, if a class has a single argument constructor is implicitly convertible from the type of its argument.
As for your other questions:
Yes, whenever it is needed.
I’m not too clear what you are asking, but if a conversion could go either way, it is ambiguous.
You have to use a cast – constructors don’t do this.
In general, if you don’t want automatic conversions from a class to other types (and mostly you don’t), it is better to provide named conversion functions (ToString, ToInt, ToX) which will never be called automatically by the compiler.
which leads on to your other two questions:
Yes, used a named function to perform at least one of the conversions. std::string does this – there is a conversion from a char * to string using a constructor, but the other way you need to use the named c_str() function.
Unfortunately, no.