CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 22
  1. #1
    Join Date
    Aug 2000
    Posts
    18

    Angry Comparison Operator Overloading

    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..

    class String
    {
    bool operator ==(char *);
    friend bool operator==(String &, char *);
    }

    I tried adding:
    friend bool operator==(String *, char *);

    but I get a compiler error.. What to do?

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449
    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

  3. #3
    Join Date
    Apr 2000
    Location
    Frederick, Maryland
    Posts
    507
    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.

    Code:
    #include <iostream>
    using namespace std;
    
    class String
    {
    private:
    	char* mData;
    
    public:
    	// default ctor
    	String(char* pData = "")
    	{
    		mData = new char[strlen(pData) + 1];
    		strcpy(mData, pData);
    	}
    	// copy ctor
    	String(const String& pString)
    	{
    		delete [] mData;
    		mData = new char[strlen(pString.mData) + 1];
    		strcpy(mData, pString.mData);
    	}
    	// assingment operator
    	String& operator = (const String& pString)
    	{
    		delete [] mData;
    		mData = new char[strlen(pString.mData) + 1];
    		strcpy(mData, pString.mData);
    		return *this;
    	}
    	// equal operator
    	friend bool operator == (const String& rhs, const String& lhs)
    	{
    		return strcmp(rhs.mData, lhs.mData) == 0 ? true : false;
    	}
    	// dtor
    	~String()
    	{
    		delete [] mData;
    	}
    };
    
    
    int main()
    {
    	String str = "Hello";
    
    	if (str == "")
    	{
    		cout << "Empty" << endl;
    	}
    	else if (str == "Hello")
    	{
    		cout << "Hello world" << endl;
    	}
    	else
    	{
    		cout << "Bye world" << endl;
    	}
    
    	return 0;
    }
    Hope it helps.

  4. #4
    Join Date
    Aug 2000
    Posts
    18
    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.
    Last edited by _illusioned; June 13th, 2002 at 01:03 PM.

  5. #5
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125
    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.

  6. #6
    Join Date
    Aug 2000
    Posts
    18
    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")

    ??

  7. #7
    Join Date
    Jan 2001
    Posts
    253
    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

  8. #8
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    Even better is

    String s("Hello");
    if (s == "hello")
    {
    }

    Very little reason to use pointers with strings.

    Jeff

  9. #9
    Join Date
    Apr 1999
    Posts
    27,449
    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

  10. #10
    Join Date
    Jun 1999
    Location
    San Diego, CA
    Posts
    600

    Using operator == for string comparison is BAD

    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.

  11. #11
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Using operator == for string comparison is BAD

    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

  12. #12
    Join Date
    Mar 2002
    Location
    Israel
    Posts
    187
    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

  13. #13
    Join Date
    Jun 1999
    Location
    San Diego, CA
    Posts
    600
    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.

  14. #14
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125
    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.

  15. #15
    Join Date
    Aug 2000
    Posts
    18
    Sounds kind of like the reasons the people who created Java gave when they decided against operator overloading.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured