Class Destructors

Class Destructors - Lecture 5: Class Destructors PIC 10B...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Lecture 5: Class Destructors PIC 10B Todd Wittman Memory Management r Repeatedly creating objects will eat up memory, especially if the object stores vectors or arrays in its private variables. r Running out of memory may cause your program to crash. r Sometimes if you run a program many times, it will start to crash. r It would be nice to have a way to remove objects that we no longer need, so that we can free up memory
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 Automatic Self-Destruct r When we create a local variable for a function, the memory blocks it used are deallocated. This saves memory. void fun () { double a; int b[10]; string c; } r All variables are destroyed when the program ends. r But dynamic arrays are not automatically destroyed. YOU control the memory blocks. r So clear any dynamic memory when you are done with it. Clean up after yourself! void fun() { int a* = new int[10]; delete[] a; } Automatic Self-Destruct r But what if our function creates a local variable that is a class? void fun() { MyClass c; } r If the class only uses primitive data types (int, double, char) and built-in classes (string, vector), then the compiler will figure out how to destroy it. r If the class uses dynamic memory (pointers), then it will NOT be destroyed automatically. r You should write a destructor for the class.
Background image of page 2
3 Sec 15.4 : Destructors r A class destructor frees up the memory taken up by the private variables of the class. r
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/27/2010 for the course PIC 157-051-20 taught by Professor Wittman during the Winter '10 term at UCLA.

Page1 / 8

Class Destructors - Lecture 5: Class Destructors PIC 10B...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online