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

c++, pointers

Solution

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

Problem

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?

Original source