assignment operator overloading in c++

kaushik picture kaushik · Apr 9, 2012 · Viewed 107.9k times · Source

I have used the following code for assignment operator overloading:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this;
     itsRadius = rhs.getRadius();
     return *this;
}

My Copy Constructor is this:

SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius();
}

In the above operator overloading code, copy constructor is called as there is a new object is being created; hence I used the below code:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this;
    itsRadius = rhs.getRadius();
    return *this;
}

Its working perfectly and the copy constructor problem is avoided, but is there any unknown issues (to me) regarding this ?

Answer

juanchopanza picture juanchopanza · Apr 9, 2012

There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.

Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.