Kvector::Kvector(float x, float y, float z) : x(x), y(y),z(z) {};
Kvector& Kvector::operator+(const Kvector& other) {
return Kvector(x + other.x, y + other.y, z + other.z);
};
Kvector& Kvector::operator*(const Kvector& other) {
return Kvector((x == 0) ? 0 : x*other.x,
(y == 0) ? y * other.y : 0,
(z == 0) ? 0 : z * other.z);
};
Kvector& Kvector::operator*(const float other) {
return Kvector(x * other, y * other, z * other);
};
void Kvector::operator+=(const Kvector& other) {
x += other.x;
y += other.y;
z += other.z;
};
Above is the definition of the operators for struct called Kvector( struct with float x y z, three simple objects and that’s it).
If my understanding of the code is correct following code should print 29 29 29. And it does so.
Kvector a(1,1,1);
a = a*29;
cout<<"poss "<<a.x << " "<<a.y<< " "<< a.z<<endl;
However if I try
Kvector a(1,1,1);
a += a*29;
cout<<"poss "<<a.x << " "<<a.y<< " "<< a.z<<endl;
It prints 1 1 1 for some reason.
So I tried the below code instead.
Kvector a(1,1,1);
a = a+ a*29;
cout<<"poss "<<a.x << " "<<a.y<< " "<< a.z<<endl;
The code above prints the following
poss -1.07374e+008 -1.07374e+008 -1.07374e+008
I expected it to print 30 30 30 since a= (1,1,1) + (1,1,1) * 29 = (1,1,1) + ( 29, 29,29) = (30,30,30)
I would deeply appreciate an explanation on this behavior.
Thank you for reading my question.
operator+= signature is :
It’s also a good practice to implement + usign += to reduce code duplication and as a free function.
Currently your code is returning a Kvector& for operator+ which return a reference to a local variable, which is obviously wrong.