Pointer to Class Object in Loop

October 28, 2012 at 21:07:35
Specs: Windows XP
Say we have code like this:
-----------------------------------------------------
int main(){
SomeClass *foo;

for(int i = 0; i < 100; i++){
foo = new SomeClass;
/*
* do something with foo
*/
}

delete foo;
return 0;
}
------------------------------------------------------
I am pretty new to pointers, and I'm curious about a few things.

If we delete "foo" after the for-loop ends, will all of the memory taken up up foo during the 100 iterations of the for-loop be deallocated? Or only the memory of foo during the last iteration? And suppose that SomeClass has a destructor. When is this destructor being called with respect to the code above?

Thanks!


See More: Pointer to Class Object in Loop

Report •

#1
October 29, 2012 at 00:12:56
Homework question?

Just delete the object within the loop. I'm not going to explain why because I suspect the purpose of the assignment is to check that you understand objects and their lifetime.


Report •

#2
October 29, 2012 at 21:15:55
Meh, I don't mind answering the random one off homework related question.

Or only the memory of foo during the last iteration?
Yes.

When is this destructor being called with respect to the code above?
You know you could write a program to test for this, but the last object will have its destructor called, because it's the only one you call delete on.

How To Ask Questions The Smart Way


Report •
Related Solutions


Ask Question