zer0Id0l
zer0Id0l

Reputation: 1444

How to interpret "operator const char*()" in operator overloading?

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

Answers (4)

Arne Mertz
Arne Mertz

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:

  1. it should not use C-cast, but C++-casts (e.g. static_cast) for the right argument
  2. operator== should be a free function, not a member function
  3. A string class should normally not have an operator const char*
  4. If the String class is implemented reasonably, the operator== should take both parameters as const references

Upvotes: 11

jfly
jfly

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

bkausbk
bkausbk

Reputation: 2790

This operator will cast it's own String to const char* and call strcmp.

Upvotes: 0

Jaffa
Jaffa

Reputation: 12719

This is an explicit call to the cast-to-const char* operator which is overloaded by your String implementation.

Upvotes: 1

Related Questions