May you let me know how the Constructors on the Heap and Constructors on the Stack difference (not only differ from on heap and on stack) and when we use?
-
I guess what you really want to know is when one should use new? – didierc Jul 02 '14 at 05:41
-
Would you like to add some code to make you question clearer? – anatolyg Jul 02 '14 at 05:54
-
You should probably clarify what you mean by "constructors on the heap/stack". – juanchopanza Jul 02 '14 at 06:33
3 Answers
They don't differ. The just use memory from different places. The same constructor method is called in both cases (as long as the types of your arguments are the same).
You may be asking about when to use new
. You use new
to allocate from the heap, and, because of RAII, when you allocate, you also construct.
class Foo{
Foo(int n){
cout << n << endl;
}
};
On the heap:
Foo *a = new Foo(5);
On the stack:
Foo a(5);
These both do the same thing, print 5.

- 1,818
- 2
- 13
- 22
Constructor on the heap is the constructor run when you create your class in the heap. Constructor on the stack is the constructor run, when you create your class in the stack.
Both of these are the same constructor.
Now, seriously. There is nothing like "constructor on the...". Class can be held in memory on the stack or on the heap, but it still contains only one constructor, which is run regardless on where do you hold your class.

- 25,318
- 18
- 90
- 167
From an object instance stand point, there is no difference between calling its constructor on the stack and calling it on the heap.
See this question: When should I use the new keyword in C++?
From the program point of view it's quite different however. On the stack, an object instance will remain "alive" as long as the scope it has been created in remain active. When that scope is left, the destructor of that object is called.
On the heap, an object destructor is not called automatically, you have to either use the delete
keyword to invoke it indirectly, or call it explicitely when the object has been constructed through a placement new.
So the only scope where an object allocated on the stack may stay alive for the whole duration of the program is the main
scope. Note that global object instances are in a special situation, because they are only required to be allocated before their first possible use.
Reasons for using new
: your program creates an object instance within a scope somewhere, but wishes to keep the instance alive longer than the scope. This seems obvious in retrospect, but there are situations where you cannot allocate instances in main
or at in the global scope. This is of course dependent of which algorithms you are using in your program.
See also: