+ 1
Why doing it with the 'new' keyword?
hello, i am wondering what is the deffirence between instantiating (or creating) an object this way: Myclass obj(cnstr); and this way: Myclass obj = new Myclass(cnstr); ????? i jus don't get the difference!!
2 ответов
+ 6
First of all.
Stack is for static memory allocation. Heap is for dynamic memory allocation.
They are the two sections of the memory layout of a process.
Myclass obj(cnstr);
is to allocate an object on the stack
Myclass obj = new Myclass(cnstr);
is to allocate an object on the heap.
as a "for now" rule. think of it this way.
You can use stack if you know how much data needs to be allocated to that object/instance (precisely) before compile time.
Or use heap if you don't know how much data allocation it'll take at run-time (especially if it takes a lot)
PS always 'delete' the memory of the object you allocated 'new' to, otherwise you'll have memory issues with your prog
0
Thank you Malu for making things clear to me.