General question on pointers

Noob here...
If you delete a pointer to an object, does it also destroy the object? If so, how can I delete the pointer but have the object remain?

Thanks,
Arthur
The delete keyword will delete the object only, not the pointer. If you want to delete the pointer, just wait until it reaches the natural end of its scope or limit the scope yourself.

This is how stuff is normally done:
1
2
3
4
5
{              // scope definition
  int* a;      // Creates a pointer
  a = new int; // Creates an object
  delete a;    // deletes the object only;
}              // the pointer is now deleted 


But if you don't want the object deleted you can do this. Note that if you don't have the address saved anywhere, your object exists but you won't be able to use it again. In this case you have a memory leak.
1
2
3
4
{              // scope definition
  int* a;      // Creates a pointer
  a = new int; // Creates an object
}              // the pointer is now deleted, the object remains 
Last edited on
Thanks! I have an array of objects called Roster, and also an array of objects called students. Each roster object will have a course name, course code and professor name, along with enrolled students. Each student object will have a student name, class standing, and number of credits. A student can appear on more the one roster, of course. My thinking was to have pointers point to a particular student to "enroll" them in a particular roster, or on multiple rosters. Am I on the right path? Thanks again.
Forgot to mention that I can only use dynamic allocations for the rosters, as I would have to be able to add or delete a roster, or add or delete a student from a roster. No vectors allowed...
I'd probably do it that way, yes. Just be sure you are only delete'ing them once. Double deletes will kill your program.
Thanks everyone. This is a school project, and it's the biggest one I've had to do so far and pointers are not my strength, though I am working at it.
Topic archived. No new replies allowed.