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 isempgiven space-> on stack or in heap? -
If the declaration
int a[4]is within a function, do all the four cells ofaget space on stack?
It depends. If
Employeehas members, that are allocated only on the stack, then the whole object is. BUT,Employeemay have pointer members andEmployee‘s constructor may allocate memory for them on the heap. Then some of the members are on the heap, some on the stack.Yes.