Memory management of Objects in C++

Understanding Memory Allocation: The Stack, the Heap, and Pointers in C++

Memory management of Objects in C++

Do you know how objects declared in C++ are stored ? . How does this affect your programming ? . in this post i m gonna explain about how objects gets stored in memory. more or like i will talk about the stack and heap then little about pointers.

class A{           //class A with method show() which is public 
public:       
    void show(){
std::cout<<"hello world"<<std::endl;
}
};
int main(){
A obj1;  //creating object in stack
obj1.show();  //accessing the property of object

A *obj2=new A();  //creating object in heap
obj2->show();     //accessing propety through pointer 
delete obj2;      //Deallocation of object 
return 0;
}

when you create an object of the class it gets stored in stack . for people coming from java they might get little surprised here, in c++ you can create objects in stack too. If you create a object in stack you generally dont need to stress about the memory management. You might already know local varibles and objects get deallocated after execution of function.

Now the interesting part is when you create an object in heap. Since cpp does not have any so called Garbage Collector you have to deallocate the memory yourself using delete function(free in c). if you want to create a variable or object in heap you can use new keyword(malloc in c) which will give you an address. Yess !! you heard right when you allocate a block of memory in heap you will get the address of it so that you can basically deallocate it later.

If you already know CPP then you know thtat pointers store addresses.so you can just make a pointer and point to that memory location. When you are done with using that you can just delete (deallocate) it.

Another thing to remeber is when you want to access the property inside the object you have two appraoches .

The first one is using '.' (dot) operator. This method is valid for the object declared inside the stack. but when you delcare object in heap you nee to use '->' this operator. Why is this differenct cause you are accessing through pointer. so this is the way you can achieve it.

PS: always deallocate the object after using or else you will get memory leak problem!!