See also Pointers and Pass by Reference in C++ Basics.
Dynamic Memory Management in C++
Declaring class objects on the stack works similarly to primitive types:
- Declare as
MyClass c; - Implicitly calls the default constructor of
MyClass - Object is allocated on the stack
- Explicit freeing not required, object deallocated when block in which it is declared ends
Dynamic allocation and deallocation of variables on the heap requires the use of keywords new and delete:
int * ip = new int; // allocate memory for integer
MyClass * c = new MyClass(); // allocate object and return pointer to address
delete c; // free the heap memory for the object
delete ip; // free the heap memory for the integer
- C++ replaces low-level C functions
malloc/freewith built-in C++ syntax using keywordsnew/delete - This example explicitly calls a default constructor (the
()are optional) to create an object withnew, but other constructors could be called instead if defined for the class type -
deleteis C++'s analogue to C'sfree- it deallocates heap memory
Dynamic arrays
We also use new/delete to manage heap memory for arrays in C++. Arrays of primitive type elements are fairly straightforward. Elements in a dynamically allocated array of primitive type are not initialized by default (similar to malloc).
int *iray = new int[n]; // makes array of n ints on heap
// ...
delete [] iray; // frees memory of array, note use of [ ] in statement!
Arrays of objects are initialized automatically using (necessary) default constructors: MyClass * array = new MyClass[6];
- Makes 6 different MyClass objects, sequentially stored in array, calls default constructor to initialize each one
- This will ONLY call the default constructor on each
- If want to call alternate constructor, we need to do separately afterwards as in the below example
- Alternate constructor call creates a temporary MyClass object and copies it into array through assignment operator
- Note the lack of
newhere -MyClass(7, 'd')object is stack allocated (not a pointer to a MyClass object)
MyClass * array = new MyClass[6];
for (int i=0; i < 6; i++)
array[i] = MyClass(7, 'd'); // fresh object made, overwrites new objects above
delete [] array; // remember to delete with [] for any array on the heap