Reputation: 407
I am making a module/library with a vector class, and I want it to do it properly.
class Vector3 {
public:
float x, y, z;
public:
Vector3();
Vector3(float a, float b, float c);
float length();
void normalize();
Vector3* dotproduct(Vector3 *rhs);
Vector3* crossproduct(Vector3 *rhs);
Vector3* add(Vector3 *rhs);
Vector3* subtract(Vector3 *rhs);
};
My doubt is in how should I return a new Vector3
after an operation.
Currently, I am dynamically allocating a new Vector3
inside each operation and then I return it.
When I use the operation I have:
Vector3 *v = v2->crossproduct(v3);
Should I change my operations to:
Vector3 Vector3::crossproduct(Vector3 *rhs){
float a = y * rhs->z - z * rhs->y;
float b = z * rhs->x - x * rhs->z;
float c = x * rhs->y - y * rhs->x;
Vector3 res(a, b, c);
return res ;
}
And use:
Vector3 v = v2->crossproduct(v3);
Or will I eventually lose the vector? Since I'm trying to make a library what is the proper way to do it? Allocate at the stack, or in the heap?
Upvotes: 2
Views: 58
Reputation: 2004
I implemente these operations like this:
Vector3 Vector3::crossproduct(const Vector3& rhs){
float a = y * rhs.z - z * rhs.y;
float b = z * rhs.x - x * rhs.z;
float c = x * rhs.y - y * rhs.x;
Vector3 res(a, b, c);
return res ;
}
To use this operator you can simply use this syntax:
Vector v1, v2;
auto product = v1.crossproduct(v2);
The return as value is most likely optimized away by copy elision, so you dont have to worry about that. And since rhs
is not modified, passing it as const ref& is the fastest way to do it.
Upvotes: 3