Operator overload in CVector class:
CVector CVector::operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp); }
and basically:
CVector a (3,1); CVector b (1,2); CVector c; c = a + b;
Thus, the object is passed by value, and then another temporary object is created. I assume that b is passed by value, a is the one that calls +, so x and y belong to a and pram.x and param.y to b. temp is returned and the copy destination statement delivers temp values ββto c?
But what about this:
CVector& CVector::operator= (const CVector& param) { x=param.x; y=param.y; return *this; }
and basically:
a=b;
Again a calls = and b is passed by reference as const (in this case, does it matter if it was passed by value?) That's where I got confused, x belonging to a is assigned to param.x to be. therefore, why this function does not work, since it can be accessed by x and y. Which means return *, it means that I know that this is the address of the object that calls the function, so * it will be the function itself, but if we return the object, we need to assign it somewhere like the previous c = temp after temp = a + b? And what does CVector & even mean that it doesnβt look like we are expecting an address of an object of type CVector?
In other words, why the function is not easy:
void CVector::operator= (const CVector& param) { x=param.x; y=param.y; }
??
Then there is this code
#include <iostream> using namespace std; class Calc { private: int value; public: Calc(int value = 0) { this->value = value; } Calc& Add(int x) { value += x; return *this; } Calc& Sub(int x) { value -= x; return *this; } Calc& Mult(int x) { value *= x; return *this; } int GetValue() { return value; } }; int main() { Calc cCalc(2); cCalc.Add(5).Sub(3).Mult(4); cout << cCalc.GetValue(); return 0; }
Now, if I also removed from the functions:
Calc Add(int x) { value += x; return *this; } Calc Sub(int x) { value -= x; return *this; } Calc Mult(int x) { value *= x; return *this; }
and used
Calc cCalc(2) cCalc.Add(5); cCalc.Sub(3); cCalc.Mult(4);
instead of the first, this will lead to the same failure. So why does the Calc & returne type allow chains.
I not only want to know how to program, because object-oriented much is written by a template (it is written this way, it is necessary if it is), the opposite of structured programming, where you need to use logic, but also know why the world of code is defined as it is, and why it is not, as I intuitively think it should be (although I only study programming for about a year).
Thanks!