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?
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.
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 +.
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.
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.
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 referencesIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With