Unlike java where the object for the class can be declared only in the heap, C++ allows us to allocate memory for an object in the stack

Object in stack

If an object is required for a shorter amount of time and if it is not required after returning from the function where the object is created, then it is best to create it in the stack.

Automatic storage class rules will be applied for objects allocated in the stack i.e. after the function is returned, the memory allocated to the object will become invalid.

obj in the following example is an object to a Rectangle class and the memory will be allocated for it in the stack segment.

Syntax:
<ClassName> <object name>;

example:
Rectangle obj;

Object in heap

When an object has to be used between multiple functions and if need the object for a longer time i.e. even after returning from the function in which the object was created then it is necessary to allocate memory for an object in a heap.

Following is the syntax on how to allocate memory for an object in the heap segment. “new” keyword should be used to allocate memory dynamically.

Syntax:
<ClassName> *<object name>  =  new <ClassName>;

example:
Rectangle *obj = new Rectangle();

Example:

#include <iostream>

class Rectangle()
{

public:
	int l;
	int b;
    
	int area(){
    	return l * b;
    }
}


int main()
{
	// Memory allocated for the object in the stack
	Rectangle obj;

	// Memory allocated for the object in heap
	Rectangle *obj2 = new Rectangle();
    
	return 0;
}

Categorized in:

Tagged in: