12.9 OPERATORS new and delete

The C++ has added (over C) two keywords “new” and “delete”. They are operators as per syntax rules. They are useful in memory allocation and de-allocation.

12.9.1 Operator new

The task of function malloc() is now handed over to operator new. The syntax of operator new is as follows:

<pointer_to_name> = new <name> [ <name_initializer> ];

The “new” operator tries to create an object <name> by allocating sizeof(<name>) bytes in the heap. Consider a declaration:

float *ft1;

Now we can allocate memory to store a float variable as

ft1 = new float;

Later on we may assign value 22.5 to it as

*ft1=22.5 ;

Alternately, we can combine these two actions in one as shown below.

ft1 = new float(22.5) ;

Well allocating memory for ...

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.