Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the following not invoke the overloaded operator== (const String &, const String &)? "cobble" == "stone"

Tags:

c++

Why does the following not invoke the overloaded operator== (const String &, const String &)?

"cobble" == "stone"
like image 985
surender Avatar asked Apr 22 '10 12:04

surender


3 Answers

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.)

like image 75
sbi Avatar answered Nov 15 '22 04:11

sbi


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.

like image 31
Vlad Avatar answered Nov 15 '22 04:11

Vlad


Because those are simple sequences of characters as in C but no instances of the string class.

like image 29
Joey Avatar answered Nov 15 '22 05:11

Joey