Why is there an implicit type conversion from pointers to bool in C++?
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?
Solution 1:
It's very common in C to write this
void f(T* ptr) {
if (ptr) {
// ptr is not NULL
}
}
You should make a const char*
constructor.
Solution 2:
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).