Reputation: 1444
I was looking at one of the implementation of String class and noticed the following overloaded == operator.
String f = "something";
String g = "somethingelse";
if (f == g)
cout << "Strings are equal." << endl;
bool operator==(String sString)
{
return strcmp(operator const char*(), (const char*)sString) == 0;
}
I understood most of the part except operator const char*()
what exactly its been used for?
I have very basic knowledge of operator overloading , can someone please throw some more light on this?
Upvotes: 6
Views: 18797
Reputation: 24626
It is an explicit call to the operator const char*()
member function. This code would do the same:
return strcmp(static_cast<const char*>(*this), (const char*)sString) == 0;
But there are more than one thing wrong with that code:
static_cast
) for the right argumentoperator==
should be a free function, not a member functionoperator const char*
String
class is implemented reasonably, the operator==
should take both parameters as const referencesUpvotes: 11
Reputation: 7990
operator const char*()
is the old-style C casting: just like you can cast an integer to float by (float)int_var, you can cast to const char*
as (const char*)string_var
. Here it cast a String to const char *
If you're familiar with the STL std::string
, then this operator const char*()
is doing basically the same job as .c_str()
there.
Upvotes: 5
Reputation: 2790
This operator will cast it's own String
to const char*
and call strcmp.
Upvotes: 0
Reputation: 12719
This is an explicit call to the cast-to-const char*
operator which is overloaded by your String
implementation.
Upvotes: 1