sometimes I see in various C++ programs, objects declared and used like so:
object *obj = new object;
obj->action();
obj->moreAction();
//etc...
Is there any benefit of doing that, instead of simply doing:
object obj;
obj.action();
obj.moreAction();
//etc
Yes - you can store the pointer in a container or return it from the function and the object will not get destroyed when the pointer goes out of scope. Pointers are used
This doesn't come for free - you need to destroy the object manually (delete
) when you no longer need it and deciding when this moment comes is not always easy, plus you might just forget to code it.
The first form, allocating objects on the heap, gives you full control of (and full responsibility for) the object's live time: you have to delete obj
explicitly.
In the second form, the object is automatically and irrevocably destroyed when obj
goes out of score (when leaving the current code block).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With