1

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.

newbie
  • 1,884
  • 7
  • 34
  • 55
  • 1
    Possible duplicate: http://stackoverflow.com/questions/1064325/why-not-use-pointers-for-everything-in-c/1064388#1064388 – JBentley Mar 25 '14 at 01:52

3 Answers3

2

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.

Community
  • 1
  • 1
sirbrialliance
  • 3,612
  • 1
  • 25
  • 15
  • *"Once you leave the current function"* is not really accurate - scope is the important thing here, not functions. *"Your program will crash or worse"* is also inaccurate - it may in fact continue to run just fine. What you will have is undefined behaviour. – JBentley Mar 25 '14 at 02:25
  • Correct on both accounts. I chose simplicity over technical detail for this answer. – sirbrialliance Mar 25 '14 at 15:11
1

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.

xxx7xxxx
  • 774
  • 6
  • 18
0

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.