How to use New and Delete Operator in C++ with examples
The new & delete operators of C++ provides a nicer means of performing Dynamic Memory Allocation (for any built-in or user-defined type) than C's malloc() and free() functions calls. The new operator allocated memory free store (in the C++ terminology, the heap is called free store), whereas, the delete operator returns the allocated memory back to the free store.
The new operator
An object is created using the new operator and when it is created inside a block, it remains to exist till it is explicitly destroyed using the delete operator. Hence, the programmer can control the lifetime of the object and it does not depend upon the block structure of the program objects of any type can be created using the new operator
pointer_variable = new data_type;
The pointer variable is of the type data_type. The new operator allocates sufficient memory to hold a data object of the type data_type and also return the address of the object created. The data_type can be of any of the valid basic datatypes. The address of the memory space allocated is stored in the pointer_variable.
The delete operator
Memory allocated using new for user-defined objects must be de-allocated using delete. When we no longer need a data object, we can destroy it and release the memory space for reuse by other data objects.
Syntax: deletepointer_variable; The pointer_variables the pointer that points to the data object that was created with a new operator. Whenever we need to free the memory allocated for an array then, we can do so as follows: delete [size] pointer_variable The size specifies the number of elements that need to be freed in the array. The challenge in using the delete operator with arrays is that the programmer needs to remember the size of the array. If we need to free the entire array, the size need not be specified.
Simple Program For New and Delete Operator in C++
Enter numbers: 22 23 24 25 26
The entered number are :
Explanation of the program
Instead of using the new operator to allocate memory, what would have happened if we had used the malloc() the allocation statements?? The program would have looked like this: a = new (int*)malloc(n* sizeof(int) ); Note that since malloc() returns a void pointer it is necessary to typecast it into an appropriate type depending on the type of pointer we have on the left side of the = operator. This gets completely avoided when we use the new operator.
© 2016-2019, Codeverb.com - All Rights Reserved