Consider the following code:
#include <iostream>
class Bar
{
public:
void foo(bool b = false, std::string name = "");
};
void Bar::foo(bool b, std::string name)
{
if (!b)
{
std::cout << "b is false" << std::endl;
}
else
{
std::cout << "b is true" << std::endl;
}
}
int main()
{
Bar myBar;
myBar.foo("bla");
return 0;
}
I guess C++ is not broken, but can anyone please explain why the output is true? I am working on VS 2010 but I also checked in ideone which runs gcc
The compiler is implicitly casting the first parameter, a char const[4]
, to bool
, and results in true
.
It's equivalent to
myBar.foo((bool)"bla");
which is also equivalent to
myBar.foo((bool)"bla", "");