I was wondering, if I create an object in main using the new keyword, then set that object (pointer) to be pointed to by a member of another class, setting the original pointer to null, where would I delete the allocated memory? I could do it in the second class’s destructor but what if that object wasn’t dynamically allocated?
Some code as an example:
World world;
Player* newPlayer = new Player("Ted");
world.setPlayer(newPlayer);
newPlayer = 0;
So now the ‘player’ member variable in World is pointing to the memory allocated by newPlayer and newPlayer is pointing to null. How should I deallocate this memory when I’m done with the World object?
You just need to call delete when you are finished. To avoid the need for this though look into making use of shared pointers as they will relieve you of the need to do this.
Edit: To answer your comment, where you call
deletedepends on your application but ensure that youdeleteit before you have allocated it.deleteit until you are sure nothing else needs to access it.A possible place would be in the destructor of your World object, but it is impossible to say without knowing details of the rest of your application. This is why
boost::shared_ptris preferable.