I am confused about the memory allocation in C++ in terms of the memory areas such as Const data area, Stack, Heap, Freestore, Heap and Global/Static area. I would like to u
Non-static data members are "inside" each instance of that class: whether that is on the stack or heap – or elsewhere – is unknown by just looking at the member in the class definition. It does not make sense to talk about the storage of non-static data members without talking about storage of the instance of the class to which they belong.
struct A {
int n; // you cannot say n is always on the stack, or always on the heap, etc.
};
int main() {
A a; // a is on the stack, so a.n is also on the stack
A *p = new A(); // *p, which means the object pointed to by p, is on the heap,
// so p->n is also on the heap
// p itself is on the stack, just like a
return 0;
}
A global; // global is neither on the stack nor on the heap, so neither is global.n
"The stack" is where variables scoped to the lifetime of a single function invocation go; this is also called "automatic storage duration". There are various stack allocation strategies and, notably, each thread has its own stack – though which is "the" stack should be clear from context. There's interesting things happening with split stacks (which allow growing and shrinking), but in that case, it's still one stack split into multiple pieces.
"The heap" is only a misnomer in that "the" refers to the "main" heap, as used by malloc and various forms of new; this is also called "dynamic storage duration".
Global variables, static data members, and function-level statics belong to neither the stack nor heap; also called "static storage duration".