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.
CodePudding user response:
this (I know its slightly different, I wanted to make the chaining clear);
Vector3D a;
Vector3D b;
Vector3D c;
c=a=b; <<<<=====
is converted by the compiler to this
c.operator=(b.operator=(a));
this only works because operator=
returns something that can be used as input to the next operator=
you ask "why return *this
"
Well the function has to return a reference to this invoked object, the only thing you have is this
. You cant return that (scuse the pun) because its not a reference its a pointer so you have to do *this
to actually get the object. The compiler sees you have declared the return type as Vector3D&
so it know to in fact return a reference not the object itself.
CodePudding user response:
An assignment in C returns the object assigned to, and it is good practice to not change this kind of behavior when you are overloading an operator (*). This allows to e.g. check the value assigned, or assigning the same value to multiple objects.
Inside a member function, this
is a pointer to the current object. So *this
is the current (assigned-to) object, and the return type Vector3D&
makes it clear that we are returning by reference, not by value.
(*) You cannot actually emulate the short-circuit evaluation of the ||
and &&
operators, which is why you should not normally overload them.