Reputation: 1980
I'm new to C++
I just want to know the difference between this statements:
Note: Enemy is base class of Ninja class
Ninja n;
Enemy * enemy = &n;
and
Enemy * enemy = new Ninja;
I also want to know when I should use any of those statements in case that they have difference.
Upvotes: 2
Views: 1045
Reputation: 3692
When you do this:
Ninja n;
you allocate the Ninja on the stack and this
Enemy * enemy = &n;
gets a pointer to that location. Once you leave the current function, the memory in the stack is reused and your Ninja* will be dangling: if you try to access it (dereference) your program will crash or worse.
When you do this:
Enemy * enemy = new Ninja;
you allocate a new Ninja object on the heap. You can continue yo use your Ninja instance until you free the memory with
delete enemy;
Check out the answers to this question to get a better idea of stack vs heap allocation.
Upvotes: 2
Reputation: 824
Ninja n;
----> n is in stack.You needn't destory it manually.
new Ninja;
----> n is in heap. you should delete it with delete enemy;
when you needn't it
Notice: when using the pointer of father class to delete the object of child class. You'd better define a virtual destructor function in both of classs.
Upvotes: 1
Reputation: 1
The new () will create an instance dynamically in memory ( like malloc () in C ) the first declaration has a statically allocated memory for the instance ( or allocated in teh stack if the declaration is inside a function ).
with new (), you will have to destroy the instance once it is no longer needed through the delete () method.
Upvotes: 0