2

I have an overloaded function called createValue:

void createValue(string, string);
void createValue(string, int);
void createValue(string, double);
void createValue(string, bool);

When I call the method obj->createValue("string name", "string value");, it calls the createValue(string, bool); overload and stores my string as a boolean.

I have changed that overloaded function to use char const* instead of just string and it works but I would like to know why this happened?

DeiDei
  • 10,205
  • 6
  • 55
  • 80
Josefhu15
  • 83
  • 2
  • 11
  • 2
    Hint: What type is `"x"`? (It's not `std::string`). – tadman Jan 27 '20 at 19:20
  • 4
    `"string value"` is a string literal. When passed as an argument it decays into a `const char*`. Converting `const char*` to `bool` is a "better" conversion than the user-defined conversion to `std::string`, so the compiler chooses the last overload. – Pete Becker Jan 27 '20 at 19:23
  • 1
    You sure the compiler isn't resolving string to char * to an int, then resolving your literal strings to a const char * -> int, and both end up devolving into the (string, bool) overload? – David W Jan 27 '20 at 19:23
  • ah! okay my different vocab on the subject kept me from finding the answer here lol. Great help thanks! – Josefhu15 Jan 27 '20 at 19:25
  • @DavidW -- there is no standard conversion from `const char*` to `int`. – Pete Becker Jan 27 '20 at 19:25
  • @Josefhu15 this is one question I don't mind seeing again. Even if you do know the "string literal is not a `string`" bit, you still must be very familiar with the nitty-gritty of conversion logic without already having encountered this problem in order to see it coming. – user4581301 Jan 27 '20 at 19:29

0 Answers0