OOP - Week 5, Lecture 2: Classes with Dynamic Memory
How Many Subjects Does a Student Take?
In the Week 2 worksheet a student had exactly 5 grades, so the class could hold them in an array of size 5. A real student does not work like that. One student is enrolled in 3 subjects this semester, another in 7, and next semester both have different numbers. The student has one grade for each subject, so the size of the array inside the object is not known when we write the class.
This is the problem of Lecture 1, now inside a class. The solution is the same: the class keeps a pointer, and it creates the array on the heap with the size it needs:
class Student {
private:
int id;
int numSubjects;
double* grades; // one grade for each subject, on the heap
};
The object itself holds only the pointer. The array is somewhere else, on the heap. A class that holds memory like this is the owner of that memory, and an owner has responsibilities. This lecture has three of them: create the array, release it, and copy it correctly. We also see how an owner makes the array bigger when a student registers for a new subject.
1. Create the Array and Release It
The constructor creates the array. new double[n] does not clear the values, so the constructor sets each grade to 0:
Student::Student(int i, int n) : id(0), numSubjects(n), grades(new double[n]) {
setId(i);
for (int k = 0; k < numSubjects; k++)
grades[k] = 0.0;
}
After that, grades is used like any array: grades[0], grades[1], and so on.
Now think about what happens when a student is destroyed. The members id, numSubjects and the pointer grades are destroyed with the object. But the array on the heap is not a member. It is only pointed to. Nobody deletes it, so it stays in memory and nobody can reach it again: a memory leak, for every student that was ever destroyed.
The destructor is where the owner gives the memory back:
Student::~Student() {
delete[] grades; // release the array of this student
}
The first rule: if the constructor creates memory with
new, the destructor must release it withdelete. For an array, usedelete[].
2. Adding a Subject: Resizing the Array
Halfway through the semester, a student registers for one more subject. The student needs one more grade, but the array has exactly numSubjects elements, and an array on the heap cannot grow. Writing grades[numSubjects] = 85; would write outside the array.
What we can do is create a new, bigger array, move everything into it, and drop the old one. This is the job of addSubject, which receives the grade of the new subject:
void Student::addSubject(double grade) {
double* bigger = new double[numSubjects + 1]; // 1. a new array, one element larger
for (int k = 0; k < numSubjects; k++)
bigger[k] = grades[k]; // 2. copy the old grades
bigger[numSubjects] = 0.0;
delete[] grades; // 3. release the old array
grades = bigger; // 4. grades points to the new array
numSubjects++;
setGrade(numSubjects - 1, grade); // 5. the grade of the new subject
}
addSubject creates a bigger one, copies the grades, releases the old array and moves the pointer.The order matters:
- Copy before you release. If you write
delete[] grades;first, the old grades are gone before you copy them. - Do not forget
delete[]. Without step 3, every call leaves the old array in memory, and nobody can reach it: a memory leak. - Do not forget step 4. Without it,
gradesstill points to the array that was just released.
After a.addSubject(85);, numSubjects is 4 and the last grade is 85. Only the array of this student changed. Another student has its own array and is not affected.
3. The Problem: The Default Copy
In Lecture 3 of Week 2 you saw that when you do not write a copy constructor, the compiler writes one for you. It copies every data member, one by one. For id and numSubjects this is perfect. For the pointer grades, it copies the address, not the array:
Student a(1, 3);
a.setGrade(0, 90);
Student b = a; // the copy constructor written by the compiler
b.setGrade(0, 50); // we want to change only b
a.print(); // a shows 50 as its first grade, not 90
This is a shallow copy: a and b have two pointers to one array.
a and b share the same grades.Two things go wrong:
- A change through one is seen through the other.
b.setGrade(0, 50)changed the array thataalso uses. - The array is released twice. At the closing brace both destructors run
delete[] grades, on the same array. Releasing the same memory twice is a serious error and the program crashes.
The same crash comes from passing a student by value to a function. The parameter is a copy, it shares the array, and when the function ends, the destructor of the copy releases the array of the original. The original student is left with a pointer to memory that does not exist anymore.
4. The Fix: A Deep Copy
We write the copy constructor ourselves. It must make a new array for the copy, and then copy the values into it, not the pointer:
Student::Student(const Student& other)
: id(other.id), numSubjects(other.numSubjects), grades(new double[other.numSubjects]) {
for (int k = 0; k < numSubjects; k++)
grades[k] = other.grades[k]; // copy the values
}
This is a deep copy: every student has its own array.
Now b.setGrade(0, 50) changes only the array of b, and each destructor releases its own array, once.
A copy is made in three places: Student b = a;, a function that takes a student by value, and a function that returns a student by value. A class with a pointer that owns memory is only safe if its copy constructor does a deep copy.
The second rule: if the class has a destructor that releases memory, write a copy constructor that makes a deep copy. In practice, the two almost always come together.
5. Putting It Together
This is the Student of Lecture 1, in the same three files, with what this lecture needs added: the grades pointer, the functions setGrade, addSubject and average, the copy constructor, and a destructor that releases the array. The constructor no longer has default parameters, because n now sizes the array, so this version has no default constructor. Click Changes since Lecture 1 to see exactly which lines are new. main makes a copy, changes only the copy, adds a subject to one student, and creates one student on the heap. The constructors and the destructor print a line, so you can see when each one runs.
#ifndef STUDENT_H
#define STUDENT_H
class Student {
private:
int id;
int numSubjects; // how many subjects the student takes
double* grades; // one grade for each subject, on the heap
public:
Student(int i, int n); // n subjects, all grades 0 at first
Student(const Student& other); // copy constructor: a deep copy
~Student(); // gives the array back
void setId(int i);
void setGrade(int index, double value);
void addSubject(double grade); // the student takes one more subject
double average() const;
void print() const;
};
#endif#include <iostream>
#include "Student.h"
using namespace std;
Student::Student(int i, int n) : id(0), numSubjects(n), grades(new double[n]) {
setId(i);
for (int k = 0; k < numSubjects; k++) // new does not clear the values
grades[k] = 0.0;
cout << "constructor " << id << endl;
}
Student::Student(const Student& other)
: id(other.id), numSubjects(other.numSubjects), grades(new double[other.numSubjects]) { // a new array
for (int k = 0; k < numSubjects; k++)
grades[k] = other.grades[k]; // copy the values, not the pointer
cout << "copy constructor " << id << endl;
}
Student::~Student() {
delete[] grades; // release the array of this student
cout << "destructor " << id << endl;
}
void Student::setId(int i) {
if (i > 0)
id = i;
}
void Student::setGrade(int index, double value) {
if (index >= 0 && index < numSubjects && value >= 0.0 && value <= 100.0)
grades[index] = value;
}
void Student::addSubject(double grade) {
double* bigger = new double[numSubjects + 1]; // 1. a new array, one element larger
for (int k = 0; k < numSubjects; k++)
bigger[k] = grades[k]; // 2. copy the old grades
bigger[numSubjects] = 0.0;
delete[] grades; // 3. release the old array
grades = bigger; // 4. grades points to the new array
numSubjects++;
setGrade(numSubjects - 1, grade); // 5. the grade of the new subject
}
double Student::average() const {
if (numSubjects == 0)
return 0.0;
double sum = 0.0;
for (int k = 0; k < numSubjects; k++)
sum += grades[k];
return sum / numSubjects;
}
void Student::print() const {
cout << "id " << id << ":";
for (int k = 0; k < numSubjects; k++)
cout << " " << grades[k];
cout << ", average " << average() << endl;
}#include <iostream>
#include "Student.h"
using namespace std;
int main() {
Student a(1, 3); // 3 subjects, so 3 grades
a.setGrade(0, 90);
a.setGrade(1, 80);
a.setGrade(2, 70);
a.print(); // the original
Student b = a; // the copy constructor: b gets its own array
b.setGrade(0, 50); // change only the copy
b.print(); // only b changed
a.print(); // a is not changed
a.addSubject(85); // a takes a 4th subject: its array is resized
a.print(); // four grades now
b.print(); // b still has three: it has its own array
Student* p = new Student(2, 2); // on the heap, with 2 subjects
p->setGrade(0, 95);
p->setGrade(1, 85);
p->print();
delete p; // the destructor releases its array
p = nullptr;
return 0;
} // b and a are destroyed here#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
Click each line of output to see what caused it.