Hi I am studying Overloading Operators at class2. Even after I read explanation, I still don't understand the things like 'operator + (const CVector&)' why does it has to be 'const CVector' and add '&'? I also wonder why ' param.x' stands for second value of x (which is 1 in this example). Thank you for reading.
Const in this case ensures that param can't be changed, which is a good thing. The & means it is a reference to an existing CVector object, and is therefore valid for input to the + operator. If it were a pointer, say, it could actually be a null pointer instead of the expected object instance, which you would never want.
That is not "canonical" op+. It is more natural to have op+ as a non-member that is implemented with a member op+=
If you want to keep the op+ as member, you should make it a const function, because it does not change the object. The foo does not change on line 24 and one could want to calculate sum of const objects.
Why a by reference parameter? The by value parameters are copies, having a copy is not necessary in the operator. Reference is "cheaper" (in certain cases).
The param should not change within the function. The const ensures that the function does not even attempt to change the param (and because param is a reference, change caller's object). Furthermore, if the bar were const object, line 24 were a syntax error without the const in the reference.