I am following a tutorial for learning C++ and have come upon a situation where we have defined a 2-dimensional vector class, Vector2D
, and then we make it a member in another class that we create in order to store the position of the mouse. I.e.,
private:
Vector2D* m_mousePosition;
Now, when I do this, and attempt to update the mouse position later on, I get an error in Xcode that points to having a null pointer for this m_mousePosition
object. I was unable to figure out why this pointer was null, but that is a different question.
I came up with a solution, and that was to explicitly allocate memory for this member pointer. In this case, I wrote:
private:
Vector2D* m_mousePosition = new Vector2D(0, 0);
And it works. However, when I close the program, it hangs with this change, and I'm wondering if not deleting the memory is causing the issue.
So the question is, what is the difference between declaring member pointers in these two different ways? Specifically, what is the effect of using new
?