0

How does operator overload below work?

I have a struct called Vector3D that has 3 float variables (x, y, z) and the code below is defined in the struct. Vector3D& operator *=(float s) { x *= s; y *= s; z *= s; return (*this); } What the code above actually does and what differentiates it from the code below? void operator *=(float s) { x *= s; y *= s; z *= s; }

28th Jul 2020, 9:02 AM
Mustafa K.
Mustafa K. - avatar
3 Respuestas
+ 6
While the effects on the objects themselves will be the same (both versions scale it just fine), returning a reference to the current object allows you to chain function or operator calls. For example, with some integer 'i' C++ would allow you to write std::cout << ( i *= 10 ); which would not be possible if the operator returned void instead of the integer. The *= operator might not be the best example in this case, but e.g. the increment and decrement operator are often used within a larger statement which requires them to return the value. Since the language allows this behaviour with default types, it is usually a good idea to write the public interface of a custom type in such a way it reflects that behaviour, as others are likely to expect your class to work like that.
28th Jul 2020, 9:51 AM
Shadow
Shadow - avatar
+ 4
Got it ~ swim ~ 👌
28th Jul 2020, 10:14 AM
Ipang
+ 4
~ swim ~ I tried compiling the version with void return value again but it still works, I didn't understand how does it not compile ? I used to overload my operators with void return value generally (except for some situations where I actually need to return a value).
28th Jul 2020, 10:27 AM
Mustafa K.
Mustafa K. - avatar