Skip to content

Instantly share code, notes, and snippets.

@BenEmdon
Last active April 19, 2017 21:49
Show Gist options
  • Save BenEmdon/b9cdad6ed88a3d570d8e78a98991ea0c to your computer and use it in GitHub Desktop.
Save BenEmdon/b9cdad6ed88a3d570d8e78a98991ea0c to your computer and use it in GitHub Desktop.
A brief explanation of the 4 basic types of arrays in C++

The Basic 4 types of Arrays in C++

For the purposes of these examples let's pretend we have the class Cat:

#include <iostream>
#include <string>
using namespace std;

class Cat {
public:
	Cat(string name = "unnamed") {
		this->name = name;
	}
	string name;
};

Statically Allocated Array of Objects

This array lives on the call stack and is deallocated at the end of the scope it was created in. When it is deallocated it also deallocates every element in it's collection.

Cat array1[10]; // default constructors are called
cout << array1[0].name << endl; // "unnamed"

Statically Allocated Array of Object Pointers

This array lives on the call stack and is deallocated at the end of the scope it was created in. When it is deallocated it does not deallocate the elements in it's collection. The

Cat* array2[10]; // no default constructors are called
cout << array2[0] << endl; // "0x0" (null pointer)
array2[0] = new Cat("Cat-Man");
cout << array2[0]->name << endl; // "Cat-Man"

// Delete data
delete array2[0]; // deletes first element

Dynamically Allocated Array of Objects

This array lives on the heap and needs to be explicitly deallocated.

Cat* array3;
array3 = new Cat[10]; // default initializers are called
cout << array3[0].name << endl; // "unnamed"

// Delete data
delete [] array3; // delete the allocated array on the heap and it's elements

Dynamically Allocated Array of Object Pointers

This array lives on the heap and needs to be explicitly deallocated. It's elements also need to be explicitly deallocated.

Cat** array4;
array4 = new Cat*[10]; // no default constructors are called
cout << array4[0] << endl; // "0x0" (null pointer)
array4[0] = new Cat("Cat-Man");
cout << array4[0]->name << endl; // "Cat-Man"

// Delete data
delete array4[0]; // must delete each object by pointer
delete [] array4; // delete the allocated array on the heap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment