< Previous | Contents | Next >

Using the new Operator

The new operator allocates memory on the heap and returns its address. You use new followed by the type of value you want to reserve space for. Thats what I do in the first line of main().

int* pHeap = new int;

The new int part of the statement allocates enough memory on the heap for one int and returns the address on the heap for that chunk of memory. The other part of the statement, int* pHeap, declares a local pointer, pHeap, which points to the newly allocated chunk of memory on the heap.

By using pHeap, I can manipulate the chunk of memory on the heap reserved for an integer. Thats what I do next; I assign 10 to the chunk of memory and then I display that value stored on the heap, using pHeap, as I would any other pointer to int. The only difference is that pHeap points to a piece of memory on the heap, not the stack.


Hin t

image

You can initialize memory on the heap at the same time you allocate it by placing a value, surrounded by parentheses, after the type. This is even easier than it sounds. For example, the following line allocates a chunk of memory on the heap for an int variable and assigns 10 to it. The statement then assigns the address of that chunk of memory to pHeap.

int* pHeap = new int(10);

image


One of the major advantages of memory on the heap is that it can persist beyond the function in which it was allocated, meaning that you can create an object on the heap in one function and return a pointer or reference to it. Thats what I demonstrate with the following line:

int* pHeap2 = intOnHeap();

300 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby


The statement calls the function intOnHeap(), which allocates a chunk of memory on the heap for an int and assigns 20 to it.

int* intOnHeap()

{

int* pTemp = new int(20); return pTemp;

}

Then, the function returns a pointer to this chunk of memory. Back in main(), the assignment statement assigns the address of the chunk of memory on the heap to pHeap2. Next, I use the returned pointer to display the value.

cout << "*pHeap2: " << *pHeap2 << "\n\n";


Hi n t

image

Up until now, if you wanted to return a value created in a function, you had to return a copy of the value. But by using dynamic memory, you can create an object on the heap in a function and return a pointer to the new object.

image