Your problem with the first version is that your compiler is trying to prevent a bug.
Your problem with the second version is that you outsmarted your compiler and successfully managed to create a bug.
Given your constructor, you want to store pointers to the float
values that are passed by reference. Since your second version now calls the constructor with references to the local variables float a, b, c;
, you created an instance of Vector3DHeap
which references them. But as soon as getUnitVector
returns, those variables no longer exist and the references stored in Vector3DHeap
became dangling references.
The solution is not to store pointers inside Vector3DHeap
or to create copies of the parameters:
Vector3DHeap::Vector3DHeap(float x, float y, float z) { this->x = new float(x); this->y = new float(y); this->z = new float(z); }
Make sure that you properly delete the stored floats, though.