Skip to main content
gamedev.net
🔒 Locked

operator =

Started by luasitdown 3 replies 450+ views
Original Post
luasitdown
luasitdown
Object& Object::operator=( const Object& ) { return *this; } the operator = assign the self to self?
blizzard999
blizzard999
You can overload the operator = with what you want.
In general it's used to copy the object passed as variable into this object.

Point2D Point2D::operator = (const Point2D& p){  this->x = p.x;  this->y = p.y;  return *this;}


Drew_Benton
Drew_Benton
Sorta, you will need to do this though:
Object& Object::operator=( const Object& RHS ){   // Copy all of the members in the Object class over to this instance   return *this;}


So for example:
class Object{   int foo;   char bar;   Object& Object::operator=( const Object& RHS )   {      foo = RHS.foo;      bar = RHS.bar;      // Copy all of the members in the Object class over to this instance      return *this;   }};
Zahlman
Zahlman
It assigns the passed-in argument to itself (you must write the code to do that; and doing so requires that you provide a name for the parameter). It also returns itself, so that you can chain the operator (i.e. so that "a=b=c=d" works as expected, making all equal to d).
Red Ant
Red Ant
In some cases, great care must be taken to avoid screwups if the source is the same as the instance the operator function is invoked on.

Example:

class MyString{private:    char* mv_pStringBuffer;    size_t mv_nSizeOfString;   // Various methods ...public:    MyString& operator = ( const MyString& rSource );};// in the cpp fileMyString& MyString::operator = ( const MyString& rSource ){    // If we already have a buffer ...    if ( mv_pStringBuffer != 0x00 )    {        deallocateBuffer(); // HAH! GOTCHA! What if this == &rSource?? We have                             // deallocated the source object's buffer as well!    }            // Allocate buffer large enough to hold content of source and do the     // coyping.    // ...        return *this;}// This version is better.MyString& MyString::operator = ( const MyString& rSource ){    // Check against self assignment.    if ( this == &rSource )    {        return *this;    }    // If we already have a buffer ...    if ( mv_pStringBuffer != 0x00 )    {        deallocateBuffer();                             }            // Allocate buffer large enough to hold content of source and do the     // coyping.    // ...        return *this;}


Of course, assigning a string to itself doesn't really make much sense, but what's to stop you from doing it anyway?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.