C++(cplusplus)-New and Delete Operators

Difference between new and malloc :

Malloc returns a void pointer,hence it is necessary to typecast it into an appropriate type of pointer.

New operator returns correct pointer type so does not involve any kind of typecasting.

int *ptr = (int *) malloc (sizeof (int) );

int ptr = new int[20];

Malloc does not call the constructor automatically while new does.

New operator can be overloaded.

NEW operator:

It allocates memory to hold a data object of any data-type and returns the address of the object.

int *ptr = new int ;

  1. Initialising memory using new operator

pointer-variable = new data-type(value) ;

float *ptr1 = new float(9.75) ;

     2. Creating memory space for any data-type like(int, arrays, structures, classes)

int *arr_ptr = new int[3][5][4] ;

DELETE operator

Delete operator destroys the bject to release the memory space for re-use.ex: delete ptr;

It calls destructor of class whose object is being destroyed.

delete arr_ptr ;

delete ptr deletes the complete array.But if the array is an array of objects, then the destructor would be called only for the first object in the array.

delete [size] arr_ptr;

It deletes the complete array and calls the destructor for each object in the array.

Here size specifies number of elements in the array to be freed.