< previous page page_980 next page >

Page 980
the entire program. In contrast, an automatic variablea local variable not declared as staticis allocated (created) when control reaches its declaration and deallocated (destroyed) when control exits the block in which the variable is declared.
With the aid of pointers, C++ provides a third category of program data: dynamic data. Dynamic variables are not declared with ordinary variable declarations; they are explicitly allocated and deallocated at execution time by means of two special operators, new and delete. When a program requires an additional variable, it uses new to allocate the variable. When the program no longer needs the variable, it uses delete to deallocate it. The lifetime of a dynamic variable is therefore the time between the execution of new and the execution of delete. The advantage of being able to create new variables at execution time is that we don't need to create any more of them than we need.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Dynamic Data Variables created during execution of a program by means of special operations. In C++, these operations are new and delete.
The new operation has two forms, one for allocating a single variable and one for allocating an array. Here is the syntax template:
0980-01.gif
The first form is used for creating a single variable of type DataType. The second form creates an array whose elements are of type DataType; the desired number of array elements is given by IntExpression. Here is an example that demonstrates both forms of the new operation:
int* intPtr;
char* nameStr;
intPtr = new int;
Creates a variable of type int and stores its address into intPtr.
nameStr = new char[6];
Creates a 6-element char array and stores the base address of the array into nameStr.

Normally, the new operator does two things: it creates an uninitialized variable (or array) of the designated type, and it returns a pointer to this variable (or the base address of an array). However, if the computer system has run

 
< previous page page_980 next page >