Use of new, .ptr and in Operator with Pointers
You will learn the use of keywords with pointers, .ptr property of arrays, and in operator of associative arrays in this lesson.
We'll cover the following
Returning a pointer using new
new
, which we have been using only for constructing class objects can be used with other types as well: structs, arrays, and fundamental types. The variables that are constructed by new
are called dynamic variables.
new
first allocates space from the memory for the variable and then constructs the variable in that space. The variable itself does not have a symbolic name in the compiled program; it will be accessed through the reference that is returned by new
.
The reference that new
returns is a different kind depending on the type of the variable:
- For class objects, it is a class variable:
Class classVariable = new Class;
- For struct objects and variables of fundamental types, it is a pointer:
Struct * structPointer = new Struct; int * intPointer = new int;
- For arrays, it is a slice:
int[] slice = new int[100];
This distinction is usually not obvious when the type is not spelled-out on the left- hand side:
auto classVariable = new Class;
auto structPointer = new Struct;
auto intPointer = new int;
auto slice = new int[100];
The following program prints the return type of new for different kinds of variables:
Get hands-on with 1400+ tech skills courses.