Deleting something doesn't automatically set the pointer to null. You'll need to nullify it yourself.
delete ptr[x];ptr[x] = NULL;
But if you take this approach, then you need to check for NULL every time you access the array.
If you need to litter your code with null-checks, then you have ownership issues that needs to be solved instead. You should not ask yourself if you need to check for null before accessing a pointer, you should ask yourself why the pointer can be deleted in the first place if you still need it.
If you delete the objects you have allocated, but then keep using the objects afterwards, your program is ill-formed. That does not mean that your program must crash or must produce an incorrect result. It may do that, but it doesn't have to. Nevertheless, your program is ill-formed.
I never said I was going to keep using the objects after I delete them. I said I was going to use the pointers and
I don't want to delete the pointers, I want to delete what the pointers are pointing to.Deleting something doesn't automatically set the pointer to null. You'll need to nullify it yourself.
delete ptr[x];ptr[x] = NULL;
But if you take this approach, then you need to check for NULL every time you access the array.
I was already planning for this though.
----------
Let me try and explain my idea.
I have two classes:
class Monster and
class Spawner.
The
Monster class will have basic functions for movement, animations and keeping track of it's health, but it's the
Spawner class that will control the creation and destruction of the Monster class instances.
So in the Spawner class I decided to create a
pointer array of Monster class and also created two functions: createMonster() and killMonster().
//! definition of the createMonster() function...//! keep in mind that the pointer array has already been given the NULL value.
void createMonster()
{
while(int x; x<=9; x++)
{
if(ptr[x]==NULL)
{
ptr[x]= new Monster;
}
}
}
//! definition of the createMonster() function...
void killMonster(int x) //! the parameter is the particular pointer in the array that I want to clear.
{
code...code...code...
//! The line of code that will destroy the instance of the Monster class so that I can make the pointer NULL, in order to be re-
//! utilized at a later date to hold a new instance of the Monster class, goes here.
ptr[x]=NULL;
}
The code might look a bit empty, but I stripped it down to the bare bones in order to clarify the idea I'm trying to convey.