I've just begun getting into classes in c++ and I was working on a class that defines 3D vectors. I was asked to overload the = operator and my professor suggested to implement it like this:
Vector3D& Vector3D::operator=(const Vector3D &rhs){
vec[0] = rhs[0];
vec[1] = rhs[1];
vec[2] = rhs[2];
return *this
}
I'm confused as to where the reference is returned and why do we use the "This" pointer. I asked my professor about this and he told me that it's necessary when we try to do succesive assignments like this:
Vector3D a;
Vector3D b;
Vector3D c=a=b;
Still, I don't understand why its necessary to have a return value as we have already updated the values before.
operator=that returnsvoid(according to the language standard), but it'll confuse people, because we all expect it to return a reference to the left-hand side. Also, not sure if you've figured this out yet, but just to save you the trouble, go read Rule of Three. You're implementing one of the three (five, if targeting C++11 or newer) operations, so you need to implement the other two (four).