Reputation: 16193
Take the simple code below. d
is a pointer on the stack that points to a demo
object on the heap. The object contains val
. This appears to be a stack variable in the context of the class, but the object is allocated on the heap . . . . so where exactly is val
?
class demo
{
int val;
public:
demo() : val(5) {};
};
demo* d = new demo();
Upvotes: 0
Views: 76
Reputation: 45450
No matter the object is stored on the stack or heap, val
always in the same memory address of demo's object as it's the first member.
§1.8.6
Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses.
Upvotes: 1
Reputation: 6031
The variable val
is located on the heap, as it is part of an object located on the heap. Each thread has its own stack, but individual objects do not. val
would be located on the stack only if d
were declared statically.
Upvotes: 2