9

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?

2
  • 6
    basic_string/operator_cmp ((7) in your case). Commented Dec 26, 2019 at 15:55
  • 2
    Fwiw, as long as one type can be converted to another, you can generally compare them. You can initialize a std::string from a c-string. Commented Dec 26, 2019 at 16:09

1 Answer 1

16

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 two std::string objects, using the first overload of operator==

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

Sign up to request clarification or add additional context in comments.

2 Comments

And, for completeness, if this overload didn't 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 two std::string objects. Which is why this operator is there: it eliminates the need for that temporary object and the overhead involved in creating and destroying it.
@PeteBecker Of course, I have added it to the answer. Thanks for pointing out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.