Lecture 12 - Oct 3, 2023
Summary
In this lecture, we discuss pointers in objects, destructors and when we need them.
Last lecture
Memory organization: stack and heap, pointers, and dynamic memory allocation.
Today
Destructors and pointers in objects.
Dynamically allocated memory
The problem when if we dynamically allocate memory in a class is to have a memory leak.
The solution is in defining destructors.
The default destructor exists by default, and is called when the object goes out of scope.
If you dynamically allocate memory in your class, you will need a destructor to free up this memory space.
Pointers to objects
Can pointers point to objects? Yes!
Pointers to objects in objects
class ComplexNum {
public:
double real;
double img;
* next;
ComplexNum
() {
ComplexNum= 0;
real = 0;
img = nullptr;
next }
~ComplexNum() {
if (next != nullptr) delete next;
}
};
int main() {
* px = new ComplexNum; // 1
ComplexNum->next = new ComplexNum; // 2
px->next->real = 8; // 3
pxdelete px; // calls the destructor
// frees up memory that p is pointing to
return 0;
}
What about next
in p
?
delete px
calls destructor on A.- Then
delete next
of A, which is B. - Then calls destructor on B ,
next
is null.