In our series of C++ programming, in this article, we talk about the new operator in C++.

So, let us begin!

Working of new operator in C++

The new operator allows us to request the allocation of memory space on a Heap structure. By using the C++ new operator, we can request additional memory during runtime i.e. at dynamic point of time during the process.

If the requested amount of memory is available on the Heap structure, the following actions will be performed by the new operator–

  • The new operator initializes the requested amount of memory space on the Heap
  • Further, it returns the address of the allocated (initialized) memory to the pointer variable.
  • The pointer variable points and represents the memory space and the value stored at it.

Having understood the working of new operator, let us now focus on the structure of the same.


Syntax of the new operator in C++

We can request memory space using the below command–

pointer-variable = new data-type;

Apart from defining a pointer variable to the requested memory, we can initialize the requested memory to a value.

Syntax:

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

Apart from requesting memory dynamically, we can even specify the size of memory blocks to be made available.

Syntax:

pointer-variable = new data-type[size];

So, in Object-oriented Programming, when we assign an object to a new operator, the following events occur:

  • The new operator allocates memory for the specified object.
  • It invokes the class constructor to initialize the specified memory space.

#c++ #cplusplus #programming-c

The new Operator in C++: Dynamic Memory Allocation
1.40 GEEK