Course Materials

OOP - Week 5, Lecture 1: Objects on the Heap

How Many Students Are in the Course?

Registration is open for this course. How many students will enroll? 40? 63? 118? Nobody knows, and the program has to be written today.

Next semester the number is different. And during the semester it changes again: some students drop the course, and a late student is added. A real program lives in a classroom that never stands still.

With what we know so far, we would write this:

Student students[50];        // the size is fixed when we write the program

This array has a problem in both directions:

  • If 63 students enroll, there is no place for the last 13.
  • If only 12 enroll, the memory of 38 students is wasted.

Making it bigger, such as 1000, only hides the problem. A student who withdraws is just as hard: a normal object lives until the closing brace of its block, so you cannot remove one student while the program is running.

We need memory that we create exactly when the program needs it, in the size we need, and that we give back when we are done. This is dynamic memory, and it lives in a different part of memory called the heap:

ย Stack (what we used so far)Heap (this lecture)
Who creates itA declaration: Student a(1, 3);You, with new
SizeFixed when you write the programCan be decided when the program runs
When is it destroyedAutomatically, at the closing braceWhen you write delete

In Week 1 you used pointers to reach variables that already existed. Here a pointer is the only way to reach an object on the heap, because the object has no name of its own.

This lecture uses a Student with an id and the number of subjects the student takes, a constructor with default parameters, and a destructor. The constructor and the destructor print a message, so we can see when they run:

class Student {
private:
    int id;
    int numSubjects;
public:
    Student(int i = 0, int n = 0);
    ~Student();
    void setId(int i);
    void print() const;
};

1. Creating and Deleting One Object

new creates an object on the heap, runs its constructor, and gives back the address of the object. We keep the address in a pointer:

Student* p = new Student(2, 4);    // the arguments go to the constructor

The pointer p is an ordinary variable on the stack. The Student object it points to is on the heap.

To call a member function through a pointer, use -> instead of the dot:

p->print();          // call print on the object p points to
(*p).print();        // the same thing, but longer

p->print() is the short way to write (*p).print(). You can also read a data member this way, if it is public: p->id.

When you no longer need the object, you must destroy it with delete:

delete p;            // runs the destructor, then gives the memory back

delete is the only thing that destroys a heap object. The closing brace destroys the pointer p, but not the object. If you forget delete, the object stays in memory until the program ends, and its destructor never runs. This is a memory leak:

Student* p = new Student(1, 3);
p = new Student(2, 4);     // the address of student 1 is lost: it can never be deleted
delete p;                    // deletes student 2 only

In this code the output has constructor 1, constructor 2 and destructor 2. There is no destructor 1, because student 1 was never deleted.

After delete p;, the pointer still holds the old address, but the object is gone. Using p now is a serious error, because p is a dangling pointer. Set it to nullptr right after the delete:

delete p;
p = nullptr;         // p now points to nothing

Three rules for delete:

  • Do not use the pointer after it.
  • Do not delete the same object twice.
  • Do not delete an object that was not created with new, such as Student a(1, 3);.

Deleting nullptr is safe and does nothing.

2. An Array of Students on the Heap

new[] creates an array of objects on the heap. Unlike Student list[3];, the size can be a variable, known only when the program runs:

int n = 3;
Student* list = new Student[n];      // n students

The array is reached through a pointer, but you use it like an array: list[0], list[1], and so on. Each list[i] is a Student object, not a pointer, so you use the dot:

list[1].print();         // list[1] is an object: dot
list[1].setId(11);

Two rules for an array created with new[]:

  • You cannot give arguments to the constructors. Every element is created by the default constructor, so the class must have one. The Student above does, because all its parameters have default values. If it did not, the program does not compile: no matching constructor for initialization of 'Student[3]'.
  • You must release it with delete[], with the brackets. delete[] calls the destructor of every element, from the last to the first, and then frees the array. Writing delete list; without the brackets is a mistake, and the behavior is undefined.
delete[] list;       // every student is destroyed
list = nullptr;
Created withReleased with
new Student(...)delete p;
new Student[n]delete[] list;

3. Putting It Together

The program below uses a stack student a, one student on the heap, and an array of three students on the heap. The constructor and the destructor print a line each, so you can see exactly when they run. The class is in three files, as in Week 3.

Students on the heapcode/oop/week-05/heap-1
has a note
#ifndef STUDENT_H
#define STUDENT_H

class Student {
private:
    int id;
    int numSubjects;                            // how many subjects the student takes

public:
    Student(int i = 0, int n = 0);              // default parameters: also the default constructor
    ~Student();

    void setId(int i);
    void print() const;
};

#endif
#include <iostream>
#include "Student.h"
using namespace std;

Student::Student(int i, int n) : id(0), numSubjects(n) {
    setId(i);
    cout << "constructor " << id << endl;
}

Student::~Student() {
    cout << "destructor " << id << endl;
}

void Student::setId(int i) {
    if (i > 0)
        id = i;
}

void Student::print() const {
    cout << "id " << id << ", subjects " << numSubjects << endl;
}
#include <iostream>
#include "Student.h"
using namespace std;

int main() {
    Student a(1, 3);                            // on the stack
    Student* p = new Student(2, 4);             // on the heap, p holds its address
    p->print();                                 // the same as (*p).print()
    delete p;                                   // the destructor runs, then the memory is freed
    p = nullptr;                                // p no longer points to anything

    cout << "array of students" << endl;
    int n = 3;                                  // the size can be a variable
    Student* list = new Student[n];             // three students, all from the default constructor
    for (int i = 0; i < n; i++)
        list[i].setId(10 + i);
    list[1].print();                            // list[1] is an object, so we use the dot
    delete[] list;                              // all three are destroyed

    cout << "end of main" << endl;
    return 0;
}                                               // a is destroyed here
Terminal
g++ main.cpp Student.cpp -o app
./app
Tip: click a line of output to jump to the code that printed it.Output hidden. Try it yourself first.

Click each line of output to see what caused it.