Why does the following not invoke the overloaded operator== (const String &, const String &)?
"cobble" == "stone"
Because in C++, string literals are of the type const char[] (also called a zero-terminated string constant), not std::string, let alone String (whatever that is).
There's a built-in operator== comparing two char* by comparing their addresses. Since arrays are implicitly convertible into pointers to their first elements (due, you guessed right, the C heritage), this operator steps in and what you compare are the addresses of these literals in memory.
Supposing your String class has an implicit conversion constructor from const char* (String::String(const char*)), you could convert one of the two to String. The other string would then be converted implicitly:
String("cobble") == "stone"
(Unless overloads of operator== taking a String and a const char* are provided for efficiency. If they are provided, they step in.)
Because implicitly existing operator==(char*, char*) matches your usage of == better.
The operator == in code "cobble" == "stone" can be matched in different ways: operator==(char[], const String&), operator==(const String&, String), operator==(const String&, const std::string&) etc., provided that the conversion from the parameter type (char*) to the type of arguments (String*, etc.) exists. However the usual char* comparison matches the input best of all.
Because those are simple sequences of characters as in C but no instances of the string class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With