Question

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

Was it helpful?

Solution

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", "");

OTHER TIPS

Because the "bla" is a char const[4], which decays to const char*, and is cast to a bool. Since it's value is not 0, the cast takes the value true. A simpler example:

#include <iostream>

int main()
{
  std::cout << std::boolalpha; // print bools nicely
  bool b = "Hello";
  std::cout << b << "\n";

}

produces

true

Bool parameter convert "bla" to true. You need to change order of your parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top