Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
zer0Id0l Avatar asked Sep 09 '13 08:09

zer0Id0l


People also ask

What is const in operator overloading?

Overloading on the basis of const type can be useful when a function returns a reference or pointer. We can make one function const, that returns a const reference or const pointer, and another non-const function, that returns a non-const reference or pointer.

Why (+) operator is also called an overloaded operator 2 points?

This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

Why do we use const char?

If you don't have the choice, using const char* gives a guarantee to the user that you won't change his data especially if it was a string literal where modifying one is undefined behavior. Show activity on this post. By using const you're promising your user that you won't change the string being passed in.

What is the correct syntax for operator overloading?

When we overload the binary operator for user-defined types by using the code: obj3 = obj1 + obj2; The operator function is called using the obj1 object and obj2 is passed as an argument to the function.


1 Answers

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
like image 197
Arne Mertz Avatar answered Sep 28 '22 14:09

Arne Mertz