Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 16: Destructors, Copy Constructors and Exam 2 Review.

Similar presentations


Presentation on theme: "ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 16: Destructors, Copy Constructors and Exam 2 Review."— Presentation transcript:

1 ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 16: Destructors, Copy Constructors and Exam 2 Review

2 Lecture outline Announcements / reminders  Lab 8 sessions are for your term project (12:00 -1:50 pm, both Wednesday and Monday sessions) attendance is required  Project group list and Exam 2 sample are available on ECE 264 teaching website Project group Today  Brief review of dynamic memory allocation  Destructors  Copy constructors  Exam 2 Review 3/19/2016 ECE 264: Lecture 16 2

3 Project Design Due on April 4 (email submission) The design should include, but is not limited to:  Requirements specification-i.e., what a user should be able to do while playing your game—which may include a use case diagram  UML class diagrams for all classes you plan to use  Program flow description typed out or in flow chart form  Planned division of work for the remainder of the term Project Leader  Each team should select a project leader  The leader is the point of contact and should coordinate all the project activities (e.g., meeting, design, demonstration, coding). The leader should divide the project tasks and assign each task to each team member based on the whole team agreement.  The division of the tasks for each team member needs to be listed in the design document. The project grading is based on the each individual’s contribution.  Recorded meeting minutes for the project should be attached to your final report. 3/19/2016 ECE 264: Lecture 16 3

4 Destructors Destructors: function called when object is destroyed and used for “object cleanup” When are these functions called?  End of function  When dynamically allocated object is freed When are destructors really necessary?  When object contains dynamically allocated data General syntax: similar to constructor ::~ () {} ECE 264: Lecture 16 43/19/2016

5 Destructor example class dynamicIntArray { private: int n_elem; // size of array int *arr; public: dynamicIntArray(); dynamicIntArray(int n); ~dynamicIntArray(); … } // Assume array initially has 0 elements dynamicIntArray::dynamicIntArray() : n_elem(0) { arr = NULL; n_elem = 0; } dynamicIntArray::dynamicIntArray(int n) : n_elem(n) { arr = new int[n_elem]; } dynamicIntArray::~dynamicIntArray() { delete [] arr; } ECE 264: Lecture 16 53/19/2016

6 Composition and destructors If a class has a data object as a member, the member destructor is automatically called  DO NOT explicitly call destructors! class tenElementArr{ private: dynamicIntArray dia; public: tenElementArr(); ~tenElementArr(); … } ECE 264: Lecture 16 6 tenElementArr::tenElementArr : dia(10) { } tenElementArr ::~tenElementArr() { /* empty destructor—arr’s destructor called automatically */ } 3/19/2016

7 Copy constructors: Constructor example Given following code, on what lines are constructors called?  Assume functions f1 and f2 have following prototype: void f(Point p); void f2(Point &p); 1. Point p1, p2; 2. Point p3(3,7); 3. Point p4 = p3; 4. p2 = p3; 5. f(p4); 6. f2(p3); 3/19/2016 ECE 264: Lecture 16 7

8 Copy constructors: Constructor example Given following code, on what lines are constructors called?  Assume functions f1 and f2 have following prototype: void f(Point p); void f2(Point &p); 1. Point p1, p2; 2. Point p3(3,7); 3. Point p4 = p3; 4. p2 = p3; 5. f(p4); 6. f2(p3); Answer: all lines except lines 4 & 6  Clearly declaring new objects in lines 1-3 Default in line 1 Parameterized in line 2  No new object in line 4  Pass by value—create new object and copy data members from argument (line 5)  Pass by reference— copy pointer (line 6) 3/19/2016 ECE 264: Lecture 16 8

9 Copy constructors We’ve seen two forms of constructors  Default  Parameterized Third type of constructor: copy constructor  Used to initialize a newly declared variable from an existing variable  Not called for assignments  Example: Point p1(2,3), p3; Point p2 = p1;// calls copy constructor p3 = p2;// uses assignment  Often generated by default ECE 264: Lecture 16 93/19/2016

10 Basic copy constructor: Point Point::Point(const Point &p) { xCoord = p.xCoord; yCoord = p.yCoord; } Argument p  Passed by reference  Specified as const Function cannot change value of p Copies all data members from p to current object 3/19/2016 ECE 264: Lecture 16 10

11 Default copy constructors By default, copy constructor performs a shallow copy  Directly copies data members from one object to the other When is a shallow copy a problem?  Pointer-based data Arrays Dynamically allocated data (scalars and arrays)  In these cases, prefer deep copy ECE 264: Lecture 16 113/19/2016

12 Example: deep copy Say we have the following class: class tenInts { private: int arr[10];... } What would copy constructor look like? 3/19/2016 ECE 264: Lecture 16 12

13 Example: deep copy (cont.) tenInts::tenInts(const tenInts &t){ for (int i=0; i < 10; i++) arr[i] = t.arr[i]; } Copy array values element by element Note: If class contained scalar values, would have to copy them as well  Copy constructor must account for all variables in class—even those that would have been handled correctly by the default shallow copy 3/19/2016 ECE 264: Lecture 16 13

14 Example: revisit dynamicIntArray Say we want to add a copy constructor to the dynamicIntArray class shown earlier: class dynamicIntArray { private: int n_elem; // size of array int *arr; public: dynamicIntArray(); dynamicIntArray(int n); ~dynamicIntArray(); … } What change(s) would we need to make to the.h file? How would we write the code for this function in the.cpp file? 3/19/2016 ECE 264: Lecture 16 14

15 Solution Add the following to the.h file: dynamicIntArray(const dynamicIntArray &); Write the function as follows in the.cpp file: dynamicIntArray::dynamicIntArray(const dynamicIntArray &d) { n_elem = d.n_elem; for (int i = 0; i < n_elem; i++) arr[i] = d.arr[i]; } 3/19/2016 ECE 264: Lecture 16 15

16 Exam 2 Review 3/19/2016 ECE 264: Lecture 16 16

17 Exam 2 Review Announcements/Reminders  Exam at 3:30 -4:45 pm on April 9 (Tuesday) General exam information Exam review: what we’ve covered since the last exam  Class relationships: association, composition, and aggregation  Initialization lists  Arrays and vectors  Strings  Dynamic memory allocation 3/19/2016 ECE 264: Lecture 16 17

18 General exam information You may also use paper-based materials such as lecture notes (printed), textbooks and other related materials. One 8.5” x 11” double-sided sheet of notes allowed All electronic devices (e.g., cellular phones, PDAs) and Computer are prohibited. Start as close to 3:30 pm (April 09) as possible and last 1 hour and 15 minutes Exam will be held in  Room S&E 222 (Monday session group)  Room S&E 214 (Wednesday session group) 3 questions, most of which have multiple parts  Short answer  Fill-in-the-blank  Understanding code (i.e., given some code, what’s output/what values do variables have?)  Writing short code sequences Sample exam2 on web site (“Exam 2 sample”) under “Schedule and Materials”“Exam 2 sample  Should at least give you idea of format  Note that topics were covered in a slightly different manner in previous years 3/19/2016 ECE 264: Lecture 8 18

19 Review: Class relationships Interactions between different objects  Basic interactions: association  Classes as data members: composition/aggregation  Can model relationships in UML Initialization lists: call one object’s constructor inside another  Most useful with composition—have user-defined object inside another user-defined object  Want to call parameterized constructor for “child” Note: default constructors are called if you do nothing 3/19/2016 ECE 264: Lecture 16 19

20 Review: Arrays Constant size list of items of same type Can initialize using comma-separated list:  int n[] = {10, 20, 30, 40, 50}; Can access individual elements using []  cout << n[1]; would print 20 Can pass arrays to functions  void printArray(int arr[], int size); Pitfalls  Indexing past array boundaries  Array name is a pointer  passed by reference 3/19/2016 ECE 264: Lecture 16 20

21 Review: Vectors Vectors allow programmer to create “arrays” that:  Are dynamically resizable  Can be assigned to one another  Can be compared for equality  Contain easier generic boundary checking Can access vectors like arrays: v[0]  Can also use vector functions Examples: vector list; //empty vector vector wordList(n); //capacity:n strings //vector of 8 integers, each initialized to 0 vector intList(8,0); 3/19/2016 ECE 264: Lecture 16 21

22 Review: Vector methods Common member functions:  bool empty(): true if vector contains no values  void pop_back(): deletes last element in vector Does not actually return the element Gives an error if vector is empty  void push_back(element): add element to end of vector  void resize(int): changes the size of vector  size_t size(): returns the size of vector  at(int): allows you to insert element in vector, but also provides boundary checking : type of elements stored in the vector (e.g. int, double)  void clear(): removes all elements from vector 3/19/2016 ECE 264: Lecture 16 22

23 Review: Strings The string class : specialized container in STL  Character array + useful functions length() empty( ) c_str()  Returns character array at(int position)  Returns char at array[position] int find(string pattern, int position);  Returns position of first occurrence of pattern or string::npos substr (int start, int len)  Gets len characters, starting at position start  Can use overloaded operators as well == makes sense; other relational operators (, =) trickier = performs string copy +, += can be used for concatenation > behave as expected 3/19/2016 ECE 264: Lecture 16 23

24 Review: Pointers Pointer: address of another object  Can get address of existing object using &  Can get value of existing pointer using *  Can assign pointers to one another using = Assignment copies address, not value at that address  Pointer declaration: * Array-pointer duality  Array name is immovable pointer to first element  Can “index” pointer like array (e.g., p[1] ) Pointer arithmetic  If p is a pointer, p++ means “point to next element” “Next element” determined by base type  Can compare pointers p == NULL  pointer points nowhere p == q  p and q point to same location 3/19/2016 ECE 264: Lecture 16 24

25 Review: Pointers (cont.) Common errors  Failing to initialize pointer  Failing to reset pointer after moving it  Incorrect/unintended syntax (most common with pointer arithmetic) Referencing objects through pointers  Use -> in place of dot operator (.) 3/19/2016 ECE 264: Lecture 16 25

26 Review: Dynamic memory allocation Use new and delete  new int allocates space for 1 integer  new int[20] allocates an array of 20 integers  As with malloc(), new returns pointer to first byte  Can directly initialize element by putting initial value in parentheses e.g. new int(3)  Use delete only to free memory allocated by new If single variable allocated: delete ptr; If array space allocated: delete [] ptr; 3/19/2016 ECE 264: Lecture 16 26

27 Final notes Next time  Operator overloading Acknowledgements: this lecture borrows heavily from lecture slides provided with the following texts: Deitel & Deitel, C++ How to Program, 8 th ed. Etter & Ingber, Engineering Problem Solving with C++, 2 nd ed. 3/19/2016 ECE 264: Lecture 16 27


Download ppt "ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 16: Destructors, Copy Constructors and Exam 2 Review."

Similar presentations


Ads by Google