*this Pointer and Overloading Operators

Hello!
I'm trying to get my head around using the this pointer, and overloading c++ operators. So, can anyone please explain to me why the below two example pieces of code are incorrect?
1.
1
2
3
4
5
6
 SQUARE SQUARE ::operator=(const SQUARE & rhs)
{
itsSide = new int;
*itsSide = rhs.GetSide();
return *this;
}


and 2.
1
2
3
4
5
VeryShort VeryShort::operator+ (const VeryShort& rhs)
{
itsVal += rhs.GetItsVal();
return *this;
}

Thanks in advance!
When overloading operator = you should be returning a reference. Also there is no need for a getter function. You can access the values directly. Generally speaking too when you call operator + it returns a copy not a modified value of the original you are mixing operator + and += up I think. So it should look something like:

1
2
3
4
5
6
VeryShort VeryShort::operator::+( const VeryShort &rhs ) const
{
    VeryShort result;
    result.itsVal = itsVal + rhs.itsVal;
    return result;
}



Or:

1
2
3
4
5
6
VeryShort VeryShort::operator::+( const VeryShort &rhs ) const
{
    VeryShort result = *this;
    result.itsVal += rhs.itsVal;
    return result;
}
Last edited on
thank you!
Topic archived. No new replies allowed.