Sunday, July 12, 2009

C++ "=" operator overloading?

I have following class, I want to overload “=” operator, I did as following but I cant get success, any one can help me please


class String


{


private:


char * name;


public:


const char * getName() const { }


void setName(const char * aname) { }


friend char * operator=(char %26amp; str, const String %26amp;rhs );


}





char * operator= (char %26amp;str, const String %26amp;rhs )


{


str = const_cast%26lt;char * %26gt;(rhs.getName())


return *str;


}





Void main()


{


String obj;


Obj.setName(“Hello World “);


Char * myString = Obj;


Cout%26lt;%26lt;myString;


}

C++ "=" operator overloading?
Sure.





Your problem here is that the parameters for your operator = are (char %26amp;, String %26amp;). You have two problems here.





First, you want to make that char *%26amp;, not char %26amp;. As defined here, you have an operator = that copies a string into a single character.





The second problem is a little bigger. You are copying a pointer here instead of doing any sort of copying of contents. When done, myString wand Obj will point at the SAME string.





While this makes for a very fast copy, you're almost guaranteed to have problems later:





1. Notice what happens to myString when Obj is deleted. myString is now pointing at deleted memory. The reverse is true as well.





2. If myString changes, so does Obj. The reverse is true as well.





3. There is no safe way to destroy the name * in your string object because you don't know how many copies were made, and if those are still in use. I'm assuming here that the implementation of setName() will allocate new memory for name, and that your full version has a destructor.





I hope this helps. Good luck.
Reply:You have completely mixed your metaphors here.





First off, your operator = only needs to take one parameter, not two -- and that parameter is whatever type you want to be able to assign TO your String.





Second, your operator = should return a String%26amp;.





Third, in order to assign a String object to a char*, you need to overload the char* cast operator.





And finally, make sure you understand that char* is just a pointer -- to actually put anything IN your string, you're going to have to dynamically allocate memory.


No comments:

Post a Comment