I've a simple project with 3 buttons
the first and second to inizialize a Class
the third to delete pointer.
I declare a private variable
OtherClass *a;
in first method call
a = new OtherClass(5);
in Second method call
a = new OtherClass(9);
in Third method i want to delete pontier
I'm wandering
delete a;
will work ??
All memory allocated for the two new statements is free ??
I know that i can use a single pointer, but i want to know if there is a way
to call new statement on a class many times, and a way to deallocate memory..
You're need to think logically about what you're doing.
At:
a = new OtherClass(5);
you're setting the value of a to store the address of the object you've created.
Then, at:
a = new OtherClass(9);
you're changing the value of a to store the address if the second object you've created.
So when you do delete a you'll be deleting whichever object has its address currently stored in a.
a can't magically hold multiple values at once. It's just like any other variable - you give it a value, and you can change that value, but it's just a single variable.
So when i delete a i will delete the the single variable !! And there are only one variable
Yes. If it helps, think of a pointer as a number. And that number is an address in memory, where the OtherClass object is stored.
A last question
to delete a
can i use
if(a != NULL) [ better if(a) ]
delete a ;
Yes, that works. You probably don't need the if statement - in most C++ implementations, it's harmless doing delete NULL; anyway, so it won't matter.
I can't remember what the C++ standard says about doing delete NULL - anyone?
Edit: keskiverto answered my question before I'd even finished asking it :)