In this blog post we will discuss some facts of new operator in c++. In c++ new operator allocates memory at runtime. It allocates memory at heap. Allocating memory at runtime is known as dynamic memory allocation. Heap is a free memory of a program and it is also called free store in c++.

Some facts of new operator in c++

  • Memory allocated by new[]  it must be deleted using delete[] operator.


In our above program we have allocated memory using new[]. if we would free memory using delete then in this case it would delete entire array but it will call the object destructor only for first object. delete[] frees all array and calls destructor of the each object containing in the array.

  • New allocates memory and call constructor of the class.
  • We should avoid to delete a memory (allocated by new ) using free() function. Let us see below code try to compile and see the output.

When we will run above program we will see output “constr called “. It means when we delete memory (allocated by new) using free() function ,the destructor does not get called and it leaks memory pointed by character pointer p.

Related Contents to follow