{{fbdoc item="title" value="Operator New Expression"}}----
Operator to dynamically allocate memory and construct data of a specified type.

{{fbdoc item="usage"}}##
	//result// = **New** //[[DataType|datatype]]//
		//or//
	//result// = **New** //[[DataType|datatype]]// ( //initializers//, ... )
		//or//
	//result// = **New** //[[DataType|datatype]]//**[** //count// **]**
##
{{fbdoc item="param"}}
	##//datatype//##
		Name of the data type to create.
	##//initializers//##
		Initial value(s) for the variable.
	##//count//##
		Exact number of elements to allocate.

{{fbdoc item="ret"}}
	A pointer of type [[DataType|datatype]] to the newly allocated data, or null pointer if the memory allocation failed.

{{fbdoc item="desc"}}
	The ##**New Expression**## operator dynamically allocates memory and constructs a specified data type.
	
	For simple types, like integers, an initial value can be given. For types without constructors, initial values can be specified for each field (either with default initializer at data-field declaration, or with initializer list as in ##**New** //datatype// (**initializers, ..**)## if all type data-fields are numeric primitives only and without any default initializers). For types with at least one constructor, the initialize list (if any) must match an existing constructor. If no initializers are given, the default values for those types will be set.
	
	##**New[] Expression**## operator is the (one-dimensional) array-version of the ##**New Expression**## operator and allocates enough memory for the specified number of objects. The default constructor for the type will be used to set the initial values for each item.
	
	Objects created with ##**New Expression**## operator must be freed with ##[[KeyPgOpDelete|Delete Statement]]## operator. Object array created with ##**New[] Expression**## operator must be freed with ##**Delete[] Statement**## operator, the array-version of ##[[KeyPgOpDelete|Delete Statement]]## operator. You cannot mix and match the different versions of the operators.
	
	Specifying an initial value of ##[[KeyPgAny|Any]]##, as in ##**New** //datatype// (**Any**)## will allocate memory for the type, but not initialize the data.  This is only valid on data types that do not have constructors (otherwise for data types with constructors, syntax of simple memory allocation with pointer conversion, like //Cptr(datatype Ptr, Allocate(Sizeof(datatype)))//, can be substituted to the invalid use of New...Any).
	
	Specifying an initial value of ##[[KeyPgAny|Any]]##, as in ##**New** //datatype//[//count//] {**Any**}## will allocate memory for the array, but not initialize the data.  This is only valid on data types that do not have constructors (otherwise for data types with constructors, syntax of simple memory allocation with pointer conversion, like //Cptr(datatype Ptr, Allocate(count * Sizeof(datatype)))//, can be substituted to the invalid use of New...Any).
	
	The total memory, in bytes, to be allocated with ##**New** //datatype//[//count//]## expression is calculated as ##//sizeof(datatype) * count//##, plus ##//sizeof(uinteger)//## if there is an implicit or explicit ##[[KeyPgDestructor|Destructor]]##.  The total memory requested in bytes to be allocated must not overflow the value that can be held by a ##[[KeyPgUinteger|Uinteger]]##.  The extra ##//uinteger//##, if allocated, stores the number of elements as part of the allocation, so that ##[[KeyPgOpDelete|Delete Statement]]## can determine the count of destructors to call.
	
	If the memory allocation fails, a null pointer is returned and no constructors are called.
	
	The dynamic memory allocation process part provided by the ##**New Expression**## operator can be overloaded for user-defined types as a member operator ##[[KeyPgOpNewOverload|New Overload]]##. The following process part for data construction can never be modified.
	
	**Note:** Using ##//pointer// = **New** //datatype//[//count//]## may be unsafe if ##//pointer//## was declared with a type different from ##//datatype//## (for sub-type polymorphism purpose for example), because the pointer arithmetic fails to access the elements if the pointer type size is different from the size of ##//datatype//## (when using ##{{fbdoc item="keyword" value="KeyPgOpPtrIndex|Operator [] (Pointer index)"}}## or adding an offset (element number) to the pointer, or even when ##**Delete[] Statement**## itself (the array-version of ##[[KeyPgOpDelete|Delete Statement]]##) must destroy the elements).

{{fbdoc item="ex"}}
{{fbdoc item="filename" value="examples/manual/operator/new.bas"}}%%(freebasic)
type Rational
	as integer	numerator, denominator
end type

scope

	' Create and initialize a "rational" and store its address.
	dim p as Rational ptr = new Rational(3, 4)
  
	' test if null return pointer
	if (p = 0) then
		print "Error: unable to allocate memory, quitting."
		end -1
	end if

	print p->numerator & "/" & p->denominator

	' Destroy the rational and give its memory back to the system. 
	delete p

end scope

scope

	' Allocate memory for 100 integers and store the address of the first one.
	dim p as integer ptr = new integer[100]

	' test if null return pointer
	if (p = 0) then
		print "Error: unable to allocate memory, quitting."
		end -1
	end if

	' Assign some values to the integers in the array.
	for i as integer = 0 to 99
		p[i] = i
	next

	' Free the entire integer array.
	delete[] p

end scope

sleep
%%

{{fbdoc item="filename" value="examples/manual/operator/nested_new.bas"}}%%(freebasic)
'' Example of nested New [] to get a 2-dimentional object array (4*3)

type UDT
	dim as integer N
	declare constructor ()
	declare destructor ()
end type

constructor UDT ()
	print "Constructor",
end constructor

destructor UDT ()
	print "Destructor",
end destructor

dim as UDT ptr ptr p = new UDT ptr [4]  '' New [] allocation for the first dimension:
										''   no internal allocation of extra uinteger because
										''   allocation of array of pointers (to UDT objects with destructor)
for I as integer = 0 to 3
	p[I] = new UDT [5]                  '' New [] allocations for the last dimension:
										''   internal allocation of an extra uinteger for each New [],
										''   because allocation of an array of UDT objects with destructor
	print
next I

for I as integer = 0 to 3
	for J as integer = 0 to 4
		p[I][J].N = I * 10 + J  '' assignment of each object array element
	next J
next I

print
for I as integer = 0 to 3
	for J as integer = 0 to 4
		print p[I][J].N,        '' display of each object array element
	next J
	print
next I
print

for I as integer = 0 to 3
	delete [] p[I]  '' Delete [] deallocations for the last dimension
	print
next I
delete [] p         '' Delete [] deallocation for the first dimension)
print

sleep
%%

		Output example:
		%%
Constructor   Constructor   Constructor   Constructor   Constructor
Constructor   Constructor   Constructor   Constructor   Constructor
Constructor   Constructor   Constructor   Constructor   Constructor
Constructor   Constructor   Constructor   Constructor   Constructor

 0             1             2             3             4
 10            11            12            13            14
 20            21            22            23            24
 30            31            32            33            34

Destructor    Destructor    Destructor    Destructor    Destructor
Destructor    Destructor    Destructor    Destructor    Destructor
Destructor    Destructor    Destructor    Destructor    Destructor
Destructor    Destructor    Destructor    Destructor    Destructor%%
{{fbdoc item="lang"}}
	- Only available in the //[[CompilerOptlang|-lang fb]]// dialect.

{{fbdoc item="diff"}}
	- New to ""FreeBASIC""

{{fbdoc item="see"}}
	- ##[[KeyPgOpDelete|Delete Statement]]##
	- ##[[KeyPgOpPlacementNew|Placement New]]##
	- ##[[KeyPgOpNewOverload|New Overload]]##

{{fbdoc item="back" value="CatPgOpMemory|Memory Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}