View Full Version : very basic doubt

23rd July 2010, 18:10
Hello all,
Well i am starting Qt with a book wherein i read that to allow object Trees(object hierarchies,i.e. child objects automatically get deleted when parent is deleted) the objects must be on heap.Why is it so;if they were on stack,using the stack pointer they could be deleted in the same way.

23rd July 2010, 18:16
Objects on the stack are deleted when the scope ends, but the ones on the heap stay until the programmer calls delete on the pointer (that was used to allocate them on heap), or the QObject parent-child relationship delete the object on the heap or the worse case: remain as a memory leak...

23rd July 2010, 19:36
Creating on the stack can give you more problems than it solves, you have less control on when the object is deleted and could cause great confusion in debugging. For example, if you use it as a child of a parent, then there is a chance that the object could be double-freed (once by going out of scope and again by a parent).