L09 Destructors and Dynamic Memory Allocation of Arrays of Objects
when is the destructor called?
building on to where we left off in L08:
- if an object is created normally (i.e., not by dynamically allocating memory), then the constructor is called upon creation, and the destructor is called when the object goes out of scope (i.e., the end of the function that the object resides in)
- e.g.
Student s;whereStudentis the class
- e.g.
- if an object is created via dynamically allocated memory, then the constructor is called when the object is created, but the destructor is never called unless the object is freed from memory (i.e., through
delete)- e.g.
Student* s = new StudentwhereStudentis the class
- e.g.
#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:
delete p- calls destructor on
p- calls
delete next;- calls destructor of
next- calls
delete next, wherenextis the next object, which is null. - thus, nothing happens
- calls
- destroys
next
- calls destructor of
- calls
- destroys
p
- calls destructor on
Double pointers are pointers that have the address of another pointer
int** p2p