Why is C++ casting the string literal I pass in as a bool rather than a string?
#include
using namespace std;
class A
{
public:
With
A(string("hello"));
it will give the expected result.
Why is it so ?
It's because of the standard conversions:
const char*
pointerbool
(section 4.12 of the standard: "A prvalue of (...) pointer (...) type can be converted to a prvalue of type bool." )string
is not considered because section 12.3 of standard explains that "Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions" and "User-defined conversions are applied only where they are unambiguous". Wouldn't you have the bool
constructor the std::string
conversion would be done implicitely. How to get what you expected ?
Just add the missing constructor for string litterals:
A(const char* v)
{
cout << v; // or convert v to string if you want to store it in a string member
}
Of course, instead of rewriting a constructor from scratch, you could opt for a delegate as suggested by 0x499602D2 in another answer.