When we instantiate a variable in c++ like int x
within a function(i.e. x is a local variable), it is allocated on top of stack of the process. But if we do int *x= new int
, the space is provided in heap.
So, my questions are:
What about objects of different classes (classes provided by c++ or user defined)? Where are their objects instantiated? For example: Let Employee is a class and we declare Employee emp;
. Where is emp
given space-> on stack or in heap?
If the declaration int a[4]
is within a function, do all the four cells of a
get space on stack?
Only space for member variable is allocated separately for each object. A separate memory location for the objects happens, because the member variables will hold different data values for different objects. Memory for objects is allocated when they are declared but not when class is defined. All objects in a given class uses same member functions.
Memory for objects is allocated when they are declared but not when class is defined. All objects in a given class uses same member functions. The member functions are created and placed in memory only once when they are defined in class definition. class item { public: int id, cost; void getdata (); }; int main () { item x,y,z; }
Methods used in the stack memory allocation in java 1 Object push (Object element): Here, an item gets pushed to the top of the stack. 2 Object pop (): Any element located at the top of the stack gets flushed and returned. ... 3 Object peek (): Here, the top element gets returned but doesn’t undergo flushing. More items...
The member functions are created and placed in the memory space only once when they are defined as part of a class specification. No separate space is allocated for member functions when the objects are created. If multiple objects of the same class type are declared then both the objects will have their own data members and separate memory space.
All local variables, no matter if from built-in types of from classes, or if they are arrays, are on the stack. All dynamic allocations are on the heap.
Of course, modifiers like static
on a local variable will make the variable be put somewhere else, so it's preserved between function calls.
Also, to confuse you further, when you create a local pointer variable, and make it point to a dynamically allocated object, e.g.
Class* a = new Class;
The actual variable a
is on the stack, but the memory it points to is on the heap.
Addendum: The C++ specification doesn't actually mention anything about stack or heap, only the behavior of different kind of variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With