0

I was thinking about the semantics of returning a class type.

Consider a simple vector class.

#ifndef __VECTOR_H__
#define __VECTOR_H__

#include <cmath>

class Vector2f {

public:
    float X;
    float Y;

    Vector2f() : X(0), Y(0) {}
    Vector2f(int x,int y) : X((float)x), Y((float)y) {}
    Vector2f(float x, float y) : X(x), Y(y) {}

    ~Vector2f() {}
    float Length() { return pow( float(X*X + Y*Y) , 0.5 ); }

    void Unit() {
        //instead of making the current vector the unit vector
        //I would like to return a unit vector
        float len = Length();
        if(len != 1.0) {
            X = X / len;
            Y = Y / len;
        }
        return;
    }


};


#endif

The function Unit() makes my current vector the unit vector, but I was thinking that I would like to instead return the unit vector as a new unit vector (I may not want to lose the old one for instance).

I started thinking that this becomes a memory management nightmare because anytime Unit() is called, it will allocate memory and later have to be deleted. Just seems like a dumb way to do it.

Vector2f Unit() {
    float len = Length();
    return new Vector2f(X/len,Y/len);
}

Is there a better way to do this? I considered maybe having the function demand a reference for a Vector2f object.

Chemistpp
  • 2,006
  • 2
  • 28
  • 48

1 Answers1

1

The payload for a Vector2f is decidedly small: 2 x float members. It's probably not worth allocating them on the heap. Instead consider capturing this type by reference or const reference for function parameters and returning it by value.

The unit function would then be:

Vector2f Unit() {
  float len = Length();
  return Vector2f(X/len,Y/len);
}
qeadz
  • 1,476
  • 1
  • 9
  • 17