RPGillespie RPGillespie - 3 months ago 8
C++ Question

Overloaded Bool/String Ambiguity

Why is C++ casting the string literal I pass in as a bool rather than a string?

#include <iostream>

using namespace std;

class A
{
public:
A(string v)
{
cout << v;
}

A(bool v)
{
cout << v;
}
};

int main()
{
A("hello");
return 0;
}


Output:
1


Is it because the compiler isn't smart enough to make the jump from char * to string and rather just assumes that bool is the closest thing to a pointer? Is my only option to make an explicit char * constructor that basically does the exact same thing as the string constructor?

Answer

If you have C++11 you can use a delegating constructor:

A(char const* s) : A(std::string(s)) { }

The reason the boolean converting-constructor is chosen over the one for std::string is because the conversion from char const* to bool is a standard conversion while the one to std::string is a user-defined conversion. Standard conversions have a greater rank than user-defined conversions.