Possible Duplicate:
Are data members allocated in the same memory space as their objects in C++?
If I declare an object like this:
void main() {
MyClass class;
}
it will be created automatically on the stack.
What happens if I do this:
class MySecondClass {
private:
MyClass class;
}
Will the member be created on the stack? If so, what happens if MySecondClass is created via new? Will this member still be on the stack?
Yes.
No. It will be stored along with the rest of the object, “on the heap” or wherever your free store is implemented, or wherever the object gets dynamically allocated (which could be some memory pool or something else).
It’s worth noting here that the terms “stack” and “heap” are generally mis-used. What you’re really asking is the following:
Does the member have automatic storage duration? Yes.
Will it do so even when the encapsulating object has dynamic storage duration? No — the dynamicness of the encapsulating object is, in a sense, “inherited”.
The practical location in memory in either case will be the stack and the free store (“heap”) respectively, and that doesn’t really matter.
And, by the way,
mainmust haveintreturn type.