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

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -