I have created a class for which I would like to overload the == operator. The name of the class is String. The problem I am running into comes into play when the object is a pointer..
String *a = new String();
if (a == "") return true; //error in VC++
the following operators are defined in the string class..
I tried adding:
friend bool operator==(String *, char *);
but I get a compiler error.. What to do?
Paul McKenzie
June 13th, 2002, 11:26 AM
I hope this is just an academic exercise, since C++ has a string class already. No need to be reinventing the wheel.
Anyway, the "" is a const char *, not a char *. Maybe that's your problem -- you need to overload for const char *. It would also help if you post the compiler error.
Regards,
Paul McKenzie
Zeeshan
June 13th, 2002, 12:15 PM
Try this code. It is not complete String class, it just show the usage of == operator. In fact you dont need to make more than one overloaded function for == function operator for operator overloading if you are not using explicit with your ctor.
String\iswa\iswa.cpp(14): error C2665: 'operator`=='' : none of the 2 overloads can convert parameter 1 from type 'String *'
if I try to call the operator directly this is the error I get. It's looking for operator ==(String *, char *) but I can't put String * in the operator because I get this error:
String.h(36): error C2803: 'operator ==' must have at least one formal parameter of class type
adding const anywhere does not help.
TheCPUWizard
June 13th, 2002, 01:38 PM
Can you provide a sample of how your are calling it. If your code looks like:
String *s = new String("Hello");
if (s == "hello")
{
}
then it should be
if ((*s) == "hello")
{
}
then the overloads will be proper.
_illusioned
June 13th, 2002, 01:46 PM
That is what i'm trying not to have in my code.. Isn't there any way to compare without first deferencing the ptr?
Isn't there a way to say..
String *a = new String();
if (a=="ADSDSA")
without having to put:
if (*a == "ADSDSA")
??
jwbarton
June 13th, 2002, 01:48 PM
When you use operator==, it has to be on an object, not on a pointer to an object. You need to dereference the pointer in order to compare the object. Otherwise, you are trying to compare the pointers, which won't work as there is no conversion between a String * and a char *.
So, using your original code, you need to do the following:
String *a = new String();
if ( *a == "" ) return true; // dereference a
Best regards,
John
jfaust
June 13th, 2002, 03:59 PM
Even better is
String s("Hello");
if (s == "hello")
{
}
Very little reason to use pointers with strings.
Jeff
Paul McKenzie
June 13th, 2002, 05:44 PM
Originally posted by _illusioned
That is what i'm trying not to have in my code.. Isn't there any way to compare without first deferencing the ptr?
Isn't there a way to say..
String *a = new String();
if (a=="ADSDSA")
without having to put:
if (*a == "ADSDSA")
?? Comparing two strings for equality requires you to test each character until a difference is found or one string terminates before the other. This is the case for char array functions such as strcmp(), and it is also the case for std::string (but this is hidden from you). Therefore you're not buying anything by specifying a (String *, char *) overload, so just stick with the one that takes a String. You have to dereference the string anyway to do the comparison, so your overload of (String *,...) really adds nothing, except maybe confusion to any other programmer trying to maintain your code. A pointer is supposed to have "pointer-like" semantics. A pointer shouldn't be taking on "a life of its own" by magically deferencing itself and doing comparisons (unless it is a smart pointer, but even in this case, it acts like a pointer).
Also, excessive overloading should be avoided. What happens is that if you excessively use overloading, the compiler will invariably come up with "ambiguous" function call errors, and worse, may not flag you for a compile error but will make erroneous and/or unoptimal conversions behind your back at runtime.
Regards,
Paul McKenzie
Anthony Mai
June 13th, 2002, 07:16 PM
It is a BAD idea to use == operator for string comparison. The reason is obvious:
if (mystring == "hello world!") {//...}
Why it is bad? There is ambiguity exactly what do you mean two strings are "equal"? It is unfortunate that alphabets of most languages have lower case and upper case. When comparing two strings, some times case doesn't matter, some times you do care about the case. Using a "==" buries that information and leaves ambiguity there.
It is better to use traditional strcmp, stricmp, strncmp etc.
Paul McKenzie
June 13th, 2002, 09:56 PM
Originally posted by Anthony Mai
It is a BAD idea to use == operator for string comparison. The reason is obvious:
if (mystring == "hello world!") {//...}
Why it is bad? There is ambiguity exactly what do you mean two strings are "equal"?
The ambiguity is when someone is creating home-made classes and there is no written rules as to what is meant by "==".
For std::string, operator == is well defined -- the comparison is done lexicographically according to the current character traits ("The C++ Standard Library", Josuttis, 11.2.7).
Regards,
Paul McKenzie
Alexis Moshinsky
June 14th, 2002, 01:05 AM
You can not use pointer and avoid dereferncing, becouse
pointer is predefined type, like int or double.
All necessary operators for these types are already defined and can not be overloaded
Anthony Mai
June 14th, 2002, 09:59 AM
What exactly is meant by lexicographically comparison? Is it dictionary order? If it is dictionary order then you are talking about "==" as case-insensitive comparison, because dictionaries never list the same word in different cases.
In real life you have both case-sensitive string comparison and case-insensitive ones. And operator== is just one. There is no way you can fit one shoe on both left and right foot. So you have to use something other than operator== at least under some situation. For the sake of avoiding confusion it is best to abandon operator== altogether and use strcmp() and stricmp().
And what about Hebrew? Hebrew is written from right to left, how does operator== work in this case?
When a symbol like "operator==" could represent too many different things, it no longer carries any useful information of what it is and becomes less and less useful. If half of the world has a first name Paul. I would have to wouder who exactly is Paul. It's better to use something that uniquely identify what it is.
TheCPUWizard
June 14th, 2002, 10:21 AM
Agreeing with all who recomment against using "==" for the same reasons, but I have two points.
1) If you dont want peoplt to use it, implement it privately, so they dont use accidently use a comipler generated one.
2) Much prefer using member/frend functions like CompareNoCase, CompareCase than older "c" library style routines.
_illusioned
June 14th, 2002, 10:35 AM
Sounds kind of like the reasons the people who created Java gave when they decided against operator overloading.
Paul McKenzie
June 14th, 2002, 11:01 AM
Originally posted by Anthony Mai
What exactly is meant by lexicographically comparison? Is it dictionary order? If it is dictionary order then you are talking about "==" as case-insensitive comparison, because dictionaries never list the same word in different cases.Exactly. If you read the reference that I stated, you will see that Josuttis explains that other types of comparisons must be explicitly coded for, either by using other algorithms and specifying locales (he has a very good one-liner that compares strings using std::compare and using the locale), changing the char_traits, or just plain old strcmp() and writing your own function or class (of course *clearly* specifiying what the comparison does).
Lippman's "Essential C++" also discusses creating a string compare that is case insensitive.
However, this still doesn't make the definition of "==" ambiguous for std::string. It is clearly stated what it does for std::string.
Regards,
Paul McKenzie
Alexis Moshinsky
June 14th, 2002, 04:34 PM
Originaly posted by _illusioned
Sounds kind of like the reasons the people who created Java gave when they decided against operator overloading.
I think that Java developers made clear mistake with eliminating operators.
Benefit of operators is so clear that i won't waste bytes
to figure it out once more. The Java.String class itself has = operator :) (if i not mistaken)
Regarding discussion between Anthony and Paul -
gentemen, i do not realize what is all about.
No == operator can cover all possible cases of string manipulations.
Standard library cover standard case(s). Otherwise You need to invent Your own stuff.
Sometimes with help of STL, sometimes without.
Anyway, the decision hasn't to be emotional, nor flow from lack skills in pointer arithmetic
Paul McKenzie
June 14th, 2002, 05:07 PM
No == operator can cover all possible cases of string manipulations.
Standard library cover standard case(s). Otherwise You need to invent Your own stuff. Sometimes with help of STL, sometimes without. You are agreeing with me. The behavior of "==" for std::string is for "standard" cases, but those standard cases are well-documented. It is not ambiguos as to what will be returned when you call std::string "==" operator.
Anything not covered by std::string "==" such as case-insensitive compare or language/locale specific comparisons have to be coded for -- just like you (and I) stated.
Regards,
Paul McKenzie
Alexis Moshinsky
June 15th, 2002, 01:27 AM
Originaly posted by Paul McKenzie
You are agreeing with me...
I'm glad to hear that not only ghost of "experts majority" does :)
However, opponents of == operator have a point. The operator
can be misleading or confusing (f.e. Person == Person)
In this case You'll waste Your expencive time to find out
that the operator do not work as You want and some workaround is needed.
Anthony Mai
June 15th, 2002, 10:31 AM
The behavior of "==" for std::string is for "standard" cases, but those standard cases are well-documented. It is not ambiguos as to what will be returned when you call std::string "==" operator.
Some where on planet earth and on some document, the behavior of "==" for std:string is well documented. Some where on some document some one's home made "==" override is also "well_documented". I am pretty sure that 90% of all source code written in planet earth are all well documented in some document some where.
"Well documented" helps, but it can not become an excuse for using ambiguous code. Document a piece of ambiguous code, unless you are directly commenting next to the source code, does NOT make a piece of code unambiguous.
How many of you memorized the whole of stdC++ document? How many memorize every thing 100% correct? None.
How often do people look into a document to check to see if he/she memoried something correctly? That seldon happen. If you think you know something (while you actually know the wrong answer), you normally don't bother read the document. The result are bugs caused by misunderstanding.
In any case, using CompareNoCase() beats using the ambiguous "==" a million times.
BTW, Paul, I tried to look up where in the document it says operator== for std:string is for lexicographically ordering, within the documentation provided with my compiler. Could not find it. std:string is just a special case of basic_string template where the object is a char.
If an average programmer needs to buy a specific book and wait several days for shipping to check exactly what an operator== is documented as, you might as well try something that makes itself clear by name.
Paul McKenzie
June 16th, 2002, 01:14 AM
Originally posted by Anthony Mai
Some where on planet earth and on some document, the behavior of "==" for std:string is well documented.Funny, I found it right here on my desk.
How many of you memorized the whole of stdC++ document? How many memorize every thing 100% correct? None.That's why you have reference material.How often do people look into a document to check to see if he/she memoried something correctly? That seldon happen. If you think you know something (while you actually know the wrong answer), you normally don't bother read the document. The result are bugs caused by misunderstanding.
OK, so what? That doesn't change the fact that "==" for std::string is not ambiguous. All you described is a person who is overconfident of his/her work and thinks they know their material when they really don't know it. Is the documentation of strcpy() ambiguous if someone codes it without knowledge of the terminating NULL byte?In any case, using CompareNoCase() beats using the ambiguous "==" a million times.Funny, because CompareNoCase() is not the same as what std::string "==" does. So you're right -- it does "beat it" because it does something different than std::string "==". If you were using std::string "==" for case insensitive comparison's then you are not using the right function. CompareNoCase() is one of the cases that need to be implemented explicitly. BTW, Paul, I tried to look up where in the document it says operator== for std:string is for lexicographically ordering, within the documentation provided with my compiler. Could not find it. std:string is just a special case of basic_string template where the object is a char.Then stop looking at lame compiler documentation and start getting good material to reference from. If you are relying on compiler docs for your reference to the C++ standard library, you'll be disappointed. If an average programmer needs to buy a specific bookIf an average programmer has no books on whatever he is programming in, then they are not average, but below average. Any book on the standard library is better than no book, and would explain what std::string is. ...and wait several days for shipping to check exactly what an operator== is documented as, you might as well try something that makes itself clear by name.Is the documentation for std::string so clandestine that I'm the only one that knows it or have it available?
Bottom line -- all of this does not take away from what I'm saying, std::string "==" is not ambiguous. That is all I'm saying. Nothing more, nothing less.
Regards,
Paul McKenzie
Anthony Mai
June 17th, 2002, 03:31 PM
Commenting on Paul's bottom line:
"all of this does not take away from what I'm saying, std::string "==" is not ambiguous. That is all I'm saying. Nothing more, nothing less. "
"Ambiguous" is a subjective term, not an objective term. Certain things may be seem ambiguous to some people but unambiguous to other people.
Is the meaning of operator "==" in std::string crystal clear to every one? I am sure it is unambiguous to some programmer with 23 years of experience plus who happen to be the student of the C++ standard maker. But there are less experience ones out there. There are only 50% of programmer who are above average, the rest are all below average. If something looks ambiguous to at least some close to average programmers, it has got to be ambiguous.
May I propose a poll on the exact meaning of std::string::operator== ?
:)
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.