I'm coding a class for Vector and Matrices and I'd like to understand how can I avoid overheads and leaks when I want to overload common operators such as +, -, * and /.
For example:
int main()
{
Vector3 aVector; //This has an address #1
Vector3 bVector; //This has another address #2
//rVector has an address #3
Vector3 rVector = aVector - bVector; //What will happen here?
}
And the vector class:
class Vector3
{
public:
float vX, vY, vZ;
Vector3& operator-(const Vector3& vector3)
{
//I want to calculate this vector with the "vector3" param
//But then what do I return?
//Test 1:
Vector3 result; //This has an address #4
result.vX = vX - vector3.vX;
result.vY = vY - vector3.vY;
result.vZ = vZ - vector3.vZ;
return result; //Did I just overwrite address #3?
//Test 2:
vX = vX - vector3.vX;
vY = vY - vector3.vY;
vZ = vZ - vector3.vZ;
return (*this); //What happened to address #3? And I just changed this vector's values and I need then again later
}
}
What's the best way to do this?
edit: One more question, if I want to do this:
Vector3 myVector = someVector - Vector3(x, y, z);
How do I code the constructor so it doesn't do anything... bad? I'm thinking it'll be creating a new class but I won't have any means to reference it after it's used in the sentence above, can this lead to problems later?