L09 Destructors and Dynamic Memory Allocation of Arrays of Objects

#ece244

when is the destructor called?

building on to where we left off in L08:

#include <iostream>
using namespace std;

class Student {
	private:
		string id;
	public:
		Student();
		~Student();
};

Student::Student() {
	// constructor
	cout << "constructor called" << endl;
}
Student::~Student() {
	// destructor
	cout << "destructor called" << endl;
}

int main(void) {
	Student x;
	Student *y = new Student;
	delete y; // if i comment this out the destructor will only be called for x
}

linked list of objects

this is a linked list of objects, each object links to another object

class ComplexNum {
	public:
		int real, img;
		ComplexNum* next;
		ComplexNum() { real = 0; img = 0; next = NULL;}
		~ComplexNum() {
			delete next; // destroy the 
		}
};

int main() {
	ComplexNum* p = new ComplexNum;
	(*p).real = 10;
	p->real = 10; // this and the above line are the same
	
	p->next = new ComplexNum; // creates a new object, next points to it
	p->next->real = 9;
	
	delete p;
}

We use a trick to avoid memory leaks here

if we deleted the top pointer without anything in the destructor, then it would leave the other pointer created inside next, without any reference to it.

So, we specify in the destructor delete next. This does the following:

Double pointers are pointers that have the address of another pointer

int** p2p