Asked during interview.
A* a=new A();A b; A *c=&b;What is the difference between 1 and 2?
I said in 2nd statement, object is created on stack and on heap in 1st. My friend said objects are always created on heap.
What is the right answer?
You're kind of right - the second block of code - assuming it appears inside a function - will have b and c on the stack, though of course depending on the type of A it may have internal pointers to heap-allocated memory (std::string, std::vector etc. are examples of this, if they're not empty and larger than any internal buffer).
That said, a itself would be on the stack in the first block too - it's only the object to which its pointed - *a, that's necessarily on the heap.
Put another way, a and c are effectively equivalent: stack based values, but the former is pointed at a heap-allocated A and the second at another stack-allocated A....
"Stack" and "heap" are implementation terms. Choice #1 allocates an A dynamically, choice #2 does the same thing automatically. Probably the program will end up using something like a heap* for dynamic storage and a stack for automatic, but that's not guaranteed.
But accepting the loose usage of the term, it is certainly not correct that "objects are always created on the heap." Maybe your friend is thinking of Java?
*not in the data structures sense of the word
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With