Lecture 11 - Sept 29, 2023
Summary
In this lecture, we discuss pointers and introduce if we have a dynamically allocated memory in an object, how do we free it when an object goes out of scope.
Last lecture
Constructors.
Today
Destructors, pointers and objects with pointers.
Memory
Memory is divided into cells. Each cell can store a byte of data (8 bits) and has an address.
A program’s memory space.
A pointer is a variable that stores and address to a byte.
Memory on stack gets freed when a function returns. All local variables in a function dissappear when the function returns or when they go out of scope.
But memory allocated on the heap dynamically has to be explicitly freed. It does not get freed when a variable goes outo f scope. It creates a memory leak if we do not free it.
Recall that in C, for every malloc
there has to be a free
. In C++, we have new add
and delete
.
The solution is to define destructors.
class Student {
private:
int *grades; string name;
public:
();
Student(int);
Student// the destructor must be public
~Student(); // no return, like constructors
// no parameters
};
...
::~Student() {
Studentif (grades != nullptr) {
delete[] grades;
}
}
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.
main.cpp
int main() {
(3); // dynamically allocates 3 integers
Student x
return 0; // destructor of x will be called if grades is !nullptr
// we will free dynamically allocated space
}
Exercise on double pointers
Double pointers (i.e., pointers to pointers) are variables that store an address too. That address is an address of a pointer.
#include <iostream>
using namespace std;
int main() {
int** p2p;
int *p, *q;
= new int;
p *p = 5;
= &p;
p2p = *p2p; // *(&p) = p
q
*q = 8; // the new int
<< **&p2p; // **(&p) = *p = the new int, prints 8
cout
return 0;
}