New (C++) - Syntax

Syntax

The syntax for new is:

p_var = new typename;

where p_var is a previously declared pointer of type typename. typename can be any basic data type or user-defined object (enum, class, and struct included). If typename is of class type, the default constructor is called to construct the object.

To initialize a new variable created via new, use the following syntax:

p_var = new type(initializer);

where initializer is the initial value assigned to the new variable, or if type is of class type, initializer is the argument(s) to a constructor.

new can also create an array:

p_var = new type ;

In this case, size specifies the length of one-dimensional array to create. The address of the first element is returned and stored into p_var, so

p_var

gives the value of the nth element (counting from 0)

Memory allocated with new must be deallocated with delete to avoid a memory leak. Arrays allocated with new must be deallocated with delete.

int *p_scalar = new int(5); //allocates an integer, set to 5. (same syntax as constructors) int *p_array = new int; //allocates an array of 5 adjacent integers. (undefined values)

Initializers cannot be specified for arrays created with new. All elements of an array are initialized with the default constructor of the type. If the type does not have a default constructor, this is a compile-time error.

Read more about this topic:  New (C++)