Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSE240 Lecture 17

CSE240 Lecture 17

Introduction to Programming Languages
new and delete
(202110)

Javier Gonzalez-Sanchez

January 17, 2017
Tweet

More Decks by Javier Gonzalez-Sanchez

Other Decks in Programming

Transcript

  1. jgs CSE 240 Introduction to Programming Languages Lecture 17: new

    and delete Dr. Javier Gonzalez-Sanchez [email protected] javiergs.engineering.asu.edu | javiergs.com PERALTA 230U Office Hours: By appointment
  2. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 3 jgs

    Example in One File: queue.cpp 1. #include <iostream> 2. using namespace std; 3. class Queue { 4. private: 5. int queue_size; 6. protected: 7. int *buffer; 8. int front; 9. int rear; 10. public: 11. Queue(int v) { 12. cout<<"constructor\n"; 13. } 14. void enqueue(int v) { 15. cout<<"enqueue\n"; 16. } 17. int dequeue(void){ 18. cout<<"dequeue\n"; return 5; 19. } 20. }; 21. int main(){ 22. Queue q1(5); 23. Queue *q2 = new Queue(5); 24. 25. // Access Object 26. q1.enqueue(2); 27. q1.enqueue(8); 28. 29. // Access Object Pointer 30. q2->enqueue(25); 31. int x = q2->dequeue(); 32. return 0; 33. }
  3. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 4 jgs

    Example in Two Files: time.h 1. class Time { 2. public: 3. Time(); // constructor 4. void setTime( int, int ); // set hour, minute 5. void printMilitary(); // print military time format 6. void printStandard(); // print standard time format 7. 8. private: 9. int hour; // 0 - 23 10. int minute; // 0 - 59 11. };
  4. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 5 jgs

    Example in Two Files: time.cpp 1. #include <iostream> 2. #include "time.h” 3. using namespace std; 4. Time::Time() { // constructor 5. hour = minute = 0; 6. } 7. void Time::setTime( int h, int m) { // Set a new mil Time 8. hour = ( h >= 0 && h < 24 ) ? h : 0; 9. minute = ( m >= 0 && m < 60 ) ? m : 0; 10.} 11.void Time::printMilitary() { // Print time in military format 12. cout << ( hour < 10 ? "0" : "" ) << hour << ":" 13. << ( minute < 10 ? "0" : "" ) << minute; // add "0" 14.}
  5. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 6 jgs

    Example in Two Files: time.cpp 15. void Time::printStandard() { // Print in standard format 16. cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) 17. << ":" << ( minute < 10 ? "0" : "" ) << minute 18. << ( hour < 12 ? " AM" : " PM" ) << endl; //endl is equal to “\n” 19. } 20. 21. int main() { 22. Time t; // new is not mandatory - instantiate object t of class Time 23. cout << "The initial military time is "; 24. t.printMilitary(); 25. cout << "\nThe initial standard time is "; 26. t.printStandard(); 27. t.setTime(15, 27); 28. cout << "\n\nMilitary time after setTime is "; 29. t.printMilitary(); 30. cout << "\nStandard time after setTime is "; 31. t.printStandard(); 32. return 0; 33. }
  6. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 8 jgs

    Outline § static, § constructor and destructor, § new and delete
  7. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 10 jgs

    Example 1. #include <iostream> 2. using namespace std; 3. class Foo { 4. public: 5. void counting(); 6. int getCounterB(); 7. static int counterA; 8. private: 9. int counterB; 10. }; 11. 12. // initial value to static member variable 13. int Foo::counterA = 0; 14. int counter = 0; A static variable is shared by all the objects from a class. Therefore, changes made to a static variable will impact all objects from the class
  8. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 11 jgs

    Example 1. #include <iostream> 2. using namespace std; 3. class Foo { 4. public: 5. void counting(); 6. int getCounterB(); 7. static int counterA; 8. private: 9. int counterB; 10. }; 11. 12. // initial value to static member variable 13. int Foo::counterA = 0; 14. int counter = 0; static versus global Variables static variables prevents functions outside the class to access the variable. As a global variable, all other functions can read/write it. A static variable is shared by all the objects from a class. Therefore, changes made to a static variable will impact all objects from the class
  9. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 12 jgs

    Example 18. void Foo::counting() { // Set a new mil Time 19. counterA++; 20. counterB++; 21. } 22. int Foo::getCounterB() { 23. return counterB; 24. } 25. int main() { 26. Foo f1, f2, f3; 27. f1.counting(); 28. f2.counting(); 29. f2.counting(); 30. f3.counting(); 31. cout << Foo::counterA<<endl; 32. cout << f1.getCounterB()<<endl; 33. cout << Foo::counterA<<endl; 34. cout << f2.getCounterB()<<endl; 35. return 0; 36. } A static variable go out of scope only if the program terminated. And it can be used even without creating an object from the class.
  10. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 14 jgs

    Constructor and Destructor A constructor in a class: § is a function whose name is same as the class name, and § is used to automatically initialize objects. A destructor in a class: § is a function whose name is same as the class name (with a ~ as prefix), and § is used to collect garbage.
  11. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 15 jgs

    Constructor and Destructor #include <iostream> using namespace std; class Queue { private: int queue_size; protected: int *buffer; int front; int rear; public: Queue(); Queue(int n); ~Queue(); }; Queue::Queue() { // constructor cout << "constructor(void)"<<endl; // code... } Queue::Queue(int n) { // constructor overload cout << "constructor (int)"<<endl; // code... } Queue::~Queue(void) { cout << "destructor"<<endl; // code... } int main () { Queue myQueue1(500); Queue myQueue2; // more code... return 0; }
  12. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 16 jgs

    Constructor and Destructor #include <iostream> using namespace std; class Queue { private: int queue_size; protected: int *buffer; int front; int rear; public: Queue(); Queue(int n); ~Queue(); }; Queue::Queue() { // constructor cout << "constructor(void)"<<endl; // code... } Queue::Queue(int n) { // constructor overload cout << "constructor (int)"<<endl; // code... } Queue::~Queue(void) { cout << "destructor"<<endl; // code... } int main () { Queue myQueue1(500); Queue myQueue2; // more code... return 0; }
  13. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 17 jgs

    When is a destructor called? § When a local object (from stack) with block scope goes out of scope. § When a program (main function) ends and global or static objects exist (OS will collect them anyway). § When the destructor is explicitly called. § When the delete keyword is called.
  14. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 19 jgs

    new and delete int main () { Queue myQueue2(500); // declare a pointer only Queue *myQueue; // reserve memory for an object myQueue = new Queue(500); // use the object myQueue->enqueue(23); myQueue2.enqueue(8); // delete will call ~Queue(); delete myQueue; ... delete myQueue2;//no needed }
  15. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 20 jgs

    new and delete with constructors and destructors #include <iostream> using namespace std; class Queue { private: int queue_size; protected: int *buffer; int front; int rear; public: Queue(); Queue(int n); ~Queue(); }; Queue::Queue() { // constructor cout << "constructor(void)"<<endl; // code... buffer = NULL; } Queue::Queue(int n) { // constructor overload cout << "constructor (int)"<<endl; // code... buffer = new int[queue_size]; } Queue::~Queue(void) { cout << "destructor"<<endl; // code... delete [] buffer; } int main () { Queue myQueue1(500); Queue myQueue2; Queue *myQueue3 = new Queue(100); // more code... delete myQueue3; return 0; }
  16. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 21 jgs

    Summary • If an object is on the stack, instead of on the heap, destructor will be called when the object goes out of scope. No delete operation is necessary. • All heap objects must be explicitly deleted before leaving the function, if they are no longer needed. • The function delete will implicitly call the destructor of the class, so that an object linked to a variable in the to-be-deleted object can be de- allocated too, i.e., using delete for variables created in the class (normally in the constructor).
  17. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 22 jgs

    delete and Array of Objects #include <iostream> using namespace std; #define size 4 class arrayObject { public: int x; double y; arrayObject() { cout << "arrayObject's constructor called" << endl; } ~arrayObject() { cout << "arrayObject's destructor called" << endl; } }; int main() { arrayObject *p, *q; // declare two pointers p = new arrayObject[size]; // Create an array of objects for (q = p; q < p + size; q++) { // Initialize the objects q->x = 10; q->y = 1.5; } for (q = p; q < p + size; q++) { cout << "Element address " << q << " Element x value: " << q->x << endl; cout << "Element address " << q << " Element y value: " << q->y << endl; } delete[] p; return 0; }
  18. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 23 jgs

    Summary § How do we delete an array of objects? We can use a loop to delete each element, § However, the language provides a library function to delete all the elements one by one without the user to explicitly use a loop: delete[] array;
  19. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 24 jgs

    Summary Java § Primitive variables (int, float, boolean) use value type. § All other variables (string, array, user defined classes) use reference type. (Java uses automatic garbage collection). C++ § Both value and reference types exist: § if value semantics is used then memory will be allocated on stack. Memory de- allocation is done automatically. § if reference semantics is used (e.g. variable is a pointer to an object), then memory must be allocated explicitly using new and explicitly de-allocated using delete
  20. Javier Gonzalez-Sanchez | CSE240 | Fall 2021 | 25 jgs

    Summary // in C++ Report r; // an object is allocated to r Report *rp1, *rp2; // two pointers declared rp1 = &r; // rp1 points to object r rp2 = new Report(); // an object is created, linked to rp2 // .. delete rp2; // in Java Report r; // an reference is allocated r = new Report (); // an object is created and linked to r
  21. jgs CSE 240 Introduction to Programming Languages Javier Gonzalez-Sanchez, Ph.D.

    [email protected] Fall 2021 Copyright. These slides can only be used as study material for the class CSE240 at Arizona State University. They cannot be distributed or used for another purpose.