2

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?

Niall
  • 30,036
  • 10
  • 99
  • 142
bpops
  • 130
  • 1
  • 9
  • This question came with a great answer about the use of the new keyword : [1]: http://stackoverflow.com/questions/655065/when-should-i-use-the-new-keyword-in-c – Logar Aug 27 '14 at 11:29

2 Answers2

4

You almost certainly don't want a pointer or new here. A simple data member should do what you want:

Vector2D m_mousePosition;

To answer your specific question:

The first declaration declares a pointer to an object, but does not create an object, or initialise the pointer to point to anything. Using this invalid pointer will give undefined behaviour; a crash if you're lucky, and arbitrary wrong behaviour if you're unlucky.

The second declaration specifies that the pointer should be initialised by dynamically creating an object, and setting the pointer to point to that. This causes a memory leak, since dynamic objects need to be deleted. Fixing that leak isn't entirely straightforward (you need either a smart pointer, or careful application of the Rule of Three), but luckily you don't have to: just use a data member as described above.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Thank you -- very clear. I changed it to a simple data member and changed relevant function calls and all seems to be working :) – bpops Aug 27 '14 at 12:37
2

The hang is quite probably caused by the debugger alerting you of a memory leak.

You should use constructors and destructors for dynamic tasks associated at runtime with the initialization of an object.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136