why we want to create an instance of object on heap space but not stack? |
There are at least three reasons:
1. Space. The stack is small compared to the heap. If you have much data, then fitting it into the stack is an issue.
2. Dynamical needs. Data does often come from the user during runtime. You cannot possibly know, how much, when you write the code. The heap allows dynamic allocation.
3. Lifetime of an object. Objects in stack live only to the end of their current scope. Objects in heap are not limited to a scope.
base* foo2 = new derived;
I don't know what the "new" does in this situation. |
Does it confuse you that there are two "situations" in that one statement?
There is an expression
new derived
. Expressions return a value.
This expression returns a memory address.
It also allocates a block of memory and constructs an object of type
derived
within that block.
The returned address is the address of that block.
That is one "situation". Just like you said:
There is a second "situation" too.
An object is created in stack space. That object is
initialized with a value.
The object has type
base*
. The object is a pointer.
The value is what the expression on the right returns.
That is no different from
int bar = 42;
where an integer object is created on stack and initialized with the value that the expression
42
returns.