C++: Dynamic Memory Allocation

Dynamic Memory Allocation

In this video, we introduce the topic of dynamic memory allocation. Dynamic memory is allocated at runtime and is deallocated when we choose it to be. The new operator is used to make allocations and the delete operator is used to deallocate them.

Below, we give a definition of a planar point class with two constructors. The first constructor is a simple default constructor that assigns the point to be the origin. The second takes in x and y coordinates.

In the main function below, we dynamically allocate a point using new with the coordinate constructor and the coordinates 3.1 and 4.9. Alterantively, if we remove the parentheses and just write "new CPoint;" we call the default constructor instead. Using new, tells the computer allocate memory for storage; we will discuss exactly how that happens more in depth later. What is returned from new is a pointer to an allocated CPoint object.

Since we need to hold on to that value to use it, we assign a pointer to it: "ipPoint". To demonstrate the allocation, we call the Print() function. Finally, we deallocate the memory with delete. Note that we should always deallocate dynamic memory or we will cause the system to run out. Failure to deallocate or delete memory causes memory leaks.

Above, we show the output from executing the program. The Print() function outputs the coordinates that were passed into the constructor.

In this main function, we use the same class to demonstrate array allocations with new. The statement "new CPoint[3]" tells the compiler to allocate space for three CPoint objects. The points are created with the default constructor, as is always the case with arrays. In the for-loop, we call Print() on each of the points. Recall that we can use the arrya index operator on pointer just like we do on arrays. Lastly, we deallocate the array with delete, using the empty brackets: []. The empty brackets tell the compiler that an array was allocated instead of a single element.

Executing this program outputs the coordinates for the three points that were allocated with the default constructor. Since all of the points are the origin, the output is trivial.