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

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Introduction to Programming Lecture 39. Copy Constructor.
ECE 264 Object-Oriented Software Development
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 21: Strings (cont.)
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Kernighan/Ritchie: Kelley/Pohl:
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 15: Class diagrams; class relationships.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 4: Continuing with C++ I/O Basics.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 3: Requirements Specification, C++ Basics.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
Pointers OVERVIEW.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Fall 2012 Lecture 8: File I/O; Introduction to classes.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 2: Software Design Cycle.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
More C++ Features True object initialisation
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 19: Exam 3 Preview.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 5: Continuing with C++ I/O Basics.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 31: Operator overloading examples, inheritance intro.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 22: Pointers.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 11: Class diagrams; class relationships.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 9: Continuing with classes.
ECE Application Programming
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 29: Operator overloading.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 18: More on inheritance and Polymorphism.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
ECE 264 Object-Oriented Software Development
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 19: Abstract Classes.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 19: Container classes; strings.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 13: Exam 1 Preview.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 17: Operator overloading and inheritance intro.
Pointers and Dynamic Arrays
ECE Application Programming
ECE 264 Object-Oriented Software Development
Andy Wang Object Oriented Programming in C++ COP 3330
ECE Application Programming
Introduction to Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
EECE.2160 ECE Application Programming
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Instructor: Dr. Michael Geiger Spring 2019 Lecture 13: Exam 1 Preview
Dynamic allocation (continued)
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Instructor: Dr. Michael Geiger Spring 2019 Lecture 23: Exam 2 Preview
EECE.2160 ECE Application Programming
Presentation transcript:

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

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

Project Design Due on April 4 ( 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

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

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

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

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

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

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

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

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 /19/2016

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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