Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences: A* a=new A(); vs. A b; A *c=&b;

Tags:

c++

pointers

Asked during interview.

  1. A* a=new A();
  2. 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?

like image 779
Ian McGrath Avatar asked Jan 29 '26 23:01

Ian McGrath


2 Answers

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....

like image 52
Tony Delroy Avatar answered Jan 31 '26 11:01

Tony Delroy


"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

like image 40
dlf Avatar answered Jan 31 '26 12:01

dlf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!