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?
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:
- it should not use C-cast, but C++-casts (e.g.
static_cast
) for the right argument
operator==
should be a free function, not a member function
- A string class should normally not have an
operator const char*
- If the
String
class is implemented reasonably, the operator==
should take both parameters as const references
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.
This is an explicit call to the cast-to-const char*
operator which is overloaded by your String
implementation.
This operator will cast it's own String
to const char*
and call strcmp.