So I’ve been writing a small math library in C++ and when dealing with a scalar multiplied by a vector I get some issues when I try to perform this operation
Vect V2;
Vect V3;
float S;
Vect V1 = V2 + S * (V2 - V3);
The Vect Value I receive in the overloaded operator * is a new Vect object and not the outcome of the (V2 – V3) part of the operation. Here’s the other relevant part of the code. If I follow the operation with the debugging the two overloaded operators work correctly by themselves but not one after the other.
Vect.h
Vect &operator - (const Vect &inVect);
friend const Vect operator*(const float scale, const Vect &inVect);
Vect.cpp
Vect &Vect::operator - (const Vect &inVect)
{
return Vect (this->x - inVect.x,this->y - inVect.y,this->z - inVect.z, 1);
}
const Vect operator*(const float scale, const Vect &inVect)
{
Vect result;
result.x = InVect.x * scale;
result.z = InVect.y * scale;
result.y = InVect.z * scale;
result.w = 1;
return result;
}
I also overloaded the + and = operator and they work as expected the only problem I encounter is the problem above.
In your
operator-, you create a temporaryVectand return a reference to that temporary. The temporary is destroyed at the end of thereturnstatement and the returned reference is left dangling. Doing anything with this reference will result in undefined behaviour.Instead, your
operator-should return aVectby value: