If I don't add this constructor, the compiler decides that param "Example" in
Example5 foo ("Example");
is of type string and works ok. But when I add this other constructor, which I thought it would give me an error, it happens that the compiler decides somehow instead, that it is no longer of type string, but of type char*. So my question is how does the compiler decide to use char* instead of string, and why? is it because char is a fundamental type?
Thanks
When faced with multiple compatible overloads, the compiler will choose the one that best fits the type of the parameter. By using Example5::Example5(const char *), the compiler is able to avoid creating a temporary std::string.
> how does the compiler decide to use char* instead of string, and why?
> is it because char is a fundamental type?
Yes. Conversion to constchar* is a standard conversion; during overload resolution, a standard conversion is preferred over a user-defined conversion (conversion to std::string).
> so, it's a kind of optimization though, isn't it?
No. It has nothing to do with optimization or with temporary objects.
For overload resolution, a standard conversion will be preferred over a user-defined conversion even if the standard conversion happens to be more expensive. http://coliru.stacked-crooked.com/a/2a05371a8dd3ad1e