What happens if a class instantiates all it's local variables on the stack (ie: int i; //An integer
on stack versus int *p; //Pointer to an int
) while the class itself is instantiated on the heap? Where are the class members?
Here's an example:
class A {
public:
int a, b; //These are instantiated on the stack, if the line were written outside a class definition.
A(int _a, int _b) {
a = _a;
b = _b;
}
};
Now, if we instantiate A like this:
#include <iostream>
A* classA = new A(1,2);
int main(void) {
std::cout << classA.a << "\t" << classA.b << endl;
return 0;
}
Where are classA.a
and classA.b
? Are they on the program stack? Are the automatically put on the heap instead, as classA
is?
Not a problem in most cases, I wouldn't think, but it might be helpful to know...
This line is factually incorrect
It depends on how the object is created - using
new
or on the stackNo, these are not instantiated on the stack. Member variables are parts of the instance data structure, and thus are allocated in the same memory chunk as the class instance. Only if the class instance is on the stack, then the instance fields are there as well.
A class is a definition of a data structure; a block of memory. It does not define where that block of memory comes from. However, all the memory for a single object comes from the same place.
Allocates all the data for A in a stack program section.
Allocates ALL the data for A on the stack (or whatever mechanism used---the stack).
Allocates all the data for A in dynamic memory.