new operator - Difference in creating an object in C++ using new keyword and not -
i'm new c++ want know difference between statements:
note: enemy base class of ninja class
ninja n; enemy * enemy = &n; and
enemy * enemy = new ninja; i want know when should use of statements in case have difference.
when this:
ninja n; you allocate ninja on stack , this
enemy * enemy = &n; gets pointer location. once leave current function, memory in stack reused , ninja* dangling: if try access (dereference) program crash or worse.
when this:
enemy * enemy = new ninja; you allocate new ninja object on heap. can continue yo use ninja instance until free memory
delete enemy; check out answers this question better idea of stack vs heap allocation.
Comments
Post a Comment