char
, int
, double
, float
, short
, etc. are all integral types. They are "known" types in the language that have fixed sizes, fixed representations, and require no compilation for the compiler to understand. The compiler can convert one to another without much issue (aside from potential narrowing conversions that can lose data - like converting from a 16 bit integer to an 8 bit int).
std::string
, on the other hand, is a class type. It cannot be directly understood by the compiler - the header file containing the class needs to be compiled and understood. This introduces several requirements, one of which is the need for a function to convert a type to your class. If you don't write a function to do this conversion, the compiler assumes one does not exist, and if you then try to use it, the compiler throws out an error.
Your third print here is asking the compiler to convert a char
type to a std::string
by invoking a cast function. This function does not exist, so the compiler throws a fit as a result.
Note that your fourth print does work because it calls a constructor function of std::string
which takes a length and a char, which does exist.