Suppose I have the following code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std; // or std::
int main()
{
string s1{ "Apple" };
cout << boolalpha;
cout << (s1 == "Apple") << endl; //true
}
My question is: How does the system check between these two? s1
is an object while "Apple"
is a C-style string literal.
As far as I know, different data types cannot be compared. What am I missing here?
Neither C or C++ have a default built-in string type. C-strings are simply implemented as a char array which is terminated by a null character (aka 0 ). This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings.
You can't compare strings with == in C. For C, strings are just (zero-terminated) arrays, so you need to use string functions to compare them. See the man page for strcmp() and strncmp(). If you want to compare a character you need to compare to a character, not a string.
To compare string literals, still use the equality and relational operators, but for objects of the string class, and not for const char*s. Using the operators for const char*s compares the pointers, and not the string literals.
There is no functionality difference between string and std::string because they're the same type.
It is because of the following compare operator defined for std::string
template< class CharT, class Traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); // Overload (7)
This allows the comparison between std::string
and the const char*
. Thus the magic!
Stealing the @Pete Becker 's comment:
"For completeness, if this overload did not exist, the comparison would still work; The compiler would construct a temporary object of type
std::string
from the C-style string and compare the twostd::string
objects, using the first overload ofoperator==
template< class CharT, class Traits, class Alloc > bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const basic_string<CharT,Traits,Alloc>& rhs ); // Overload (1)
Which is why this operator(i.e. overload 7) is there: it eliminates the need for that temporary object and the overhead involved in creating and destroying it."
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