Consider the class foo
with two constructors defined like this:
class foo
{
public:
foo(const std::string& filename) {std::cout << "ctor 1" << std::endl;}
foo(const bool some_flag = false) {std::cout << "ctor 2" << std::endl;}
};
Instantiate the class with a string literal, and guess which constructor is called?
foo a ("/path/to/file");
Output:
ctor 2
I don't know about you, but I don't find that the most intuitive behavior in programming history. I bet there is some clever reason for it, though, and I'd like to know what that might be?
It's very common in C to write this
You should make a
const char*
constructor.You're passing a char* to the foo constructor. This can be implicitly converted to a boolean (as can all pointers) or to a std::string. From the compiler's point of view, the first conversion is "closer" than the second because it favours standard conversions (i.e. pointer to bool) over user provided conversions (the std::string(char*) constructor).
You're confusing two issues. One is that
"blah"
can be implicitly converted to astring
and the other is thatconst char*
can be implicitly converted into a boolean. It's very logical to see the compiler go to the implicit conversion which minimizes the total amount of conversions necessary.