Concepts (this lecture) CSC 143. Classes with Dynamically Allocated Data. List of ints w/dups (cont.) Example: List of ints with dups.

Similar documents
CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Intermediate Programming & Design (C++) Classes in C++

Object-Oriented Principles and Practice / C++

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

Object-Oriented Principles and Practice / C++

Assignment of Structs

Object-Oriented Principles and Practice / C++

Constructor - example

ComS 228 Exam 1. September 27, 2004

การทดลองท 8_2 Editor Buffer Array Implementation

Assignment of Objects

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Programming, numerics and optimization

CS201- Introduction to Programming Current Quizzes

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

Object-Oriented Programming for Scientific Computing

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

G52CPP C++ Programming Lecture 13

CMPT 135: Midterm Answer Key

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

CSE143 Exam with answers Problem numbering may differ from the test as given. Midterm #2 February 16, 2001

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

COMP 2355 Introduction to Systems Programming

More class design with C++ Starting Savitch Chap. 11

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Class Vector: Interface CSE 143. Dynamic Memory In Classes [Chapter 4, p ] Vector Implementation. Many Ways to Implement. Draw the picture!

Assignment 4: SkipList

pointers & references

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

CPSC 427: Object-Oriented Programming

CSC1322 Object-Oriented Programming Concepts

Instantiation of Template class

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Written by John Bell for CS 342, Spring 2018

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

Due Date: See Blackboard

Programming Abstractions

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

CSE 303: Concepts and Tools for Software Development

Vector and Free Store (Vectors and Arrays)

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

LECTURE 03 LINKED LIST

Midterm Review. PIC 10B Spring 2018

CSE 333 Midterm Exam July 24, Name UW ID#

Pointers II. Class 31

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Comp151. Generic Programming: Container Classes

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

EECE.3220: Data Structures Spring 2017

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

CMSC 341 Lecture 10 Binary Search Trees

COSC 2P95 Lab 5 Object Orientation

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Constructors, Destructors, and Assignment Operators. Literature: Effective C++, Third Edition Chapter 2


Object-Oriented Programming, Iouliia Skliarova

More Advanced Class Concepts

CS 2604 Homework 1 C++ Review Summer I 2003

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

Do not write in this area TOTAL. Maximum possible points: 75

Motivation for Templates

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

CS 2604 Homework 1 Greatest Hits of C++ Summer 2000

Copy Constructor, Assignment, Equality

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

CPSC 427: Object-Oriented Programming

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Classes and Pointers: Some Peculiarities

A brief introduction to C++

Object-Oriented Programming

Name: Username: I. 10. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

III. Classes (Chap. 3)

Introduction Of Classes ( OOPS )

Class and Function Templates

CS 2604 Homework 2 Solution for Greatest Hits of C++ Fall 2000

a data type is Types

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Binary Tree Node Relationships. Binary Trees. Quick Application: Expression Trees. Traversals

Binary Trees. For example: Jargon: General Binary Trees. root node. level: internal node. edge. leaf node. Data Structures & File Management

Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle s(0,0,4,4)

Part I: Short Answer (12 questions, 65 points total)

class objects instances Fields Constructors Methods static

CS 101: Computer Programming and Utilization

Financial computing with C++

04-19 Discussion Notes

Functions, Pointers, and the Basics of C++ Classes

Set Implementation Version 1

Financial computing with C++

Transcription:

CSC 143 Classes with Dynamically Allocated Data Concepts (this lecture) Constructors and destructors for dynamic data The this pointer Deep versus shallow copy Defining assignment (operator=) Copy constructor Standard components of a C++ class (how to create a proper user-defined type) CSC 143I 1 CSC 143I 2 Example: List of ints with dups New class IntList Instances of IntList hold collections of integers An int may appear more than once in an IntList Operations Constructors: Create empty IntList; create IntList with room for n elements initially Queries: determine size of an IntList; find out if a given number appears in an IntList List of ints w/dups (cont.) Operations (cont) Modify: add a number to an IntList, expanding the list to make room if needed Addition: create a new list that contains all of the elements from two other lists Stream output: << CSC 143I 3 CSC 143I 4 Using IntLists An IntList works like this IntList L, M, N; L.add(17); L.add(42); L.add(18).add(23); if (L.isMember(17)) cout << works << endl; else cout << is broken << endl; M.add(143); N = M + L; CSC 143I 5 IntList Representation In file intlist.h class IntList { public: private: int arraysz;// current size of array L int sz; int *L; ; // current # items in list // array containing list // elements in L[0,..,sz-1] // L[sz,..,arraysz-1] is // free space. CSC 143I 6

IntList Interface In file intlist.h class IntList { public: // constructors IntList( ); // create empty IntList IntList(int n);// create empty IntList // with free space // for n ints // destructor ~IntList( ); CSC 143I 7 IntList Interface (cont) // = # elements in this IntList int size( ) const; // = n is in this IntList bool ismember(int n) const; // add n to this IntList IntList& add(int n); // = new IntList with all elements from // *this followed by all elements from t const IntList operator+(const IntList &t) const; // stream output friend ostream& operator<<(ostream &s, const IntList &t); CSC 143I 8 ; Constructors Need to initialize private data, including allocating an array to hold the list data. Initial size of array is some small number if the client doesn t request anything specific. In file intlist.cpp static const int initialsz = 4; // initial size of array if none given // (unrealistically small to make it // easier to test/demonstrate // operation of IntList::add) CSC 143I 9 Constructors (cont) In file intlist.cpp (cont) // create empty list (default size) IntList::IntList( ) { arraysz = initialsz; sz = 0; //create empty IntList with space for n //ints IntList::IntList(int n) { arraysz = n; sz = 0; CSC 143I 10 Dynamic Data Management An IntList refers to dynamically allocated data. The array needs to be deleted when the IntList no longer exists. Array allocated here by constructor void f( ) { IntList L1; Automatic storage used by L1 reclaimed here (arraysz, sz, L) When function f terminates, the space holding ints and pointers of L1 is recycled. If nothing further is done, the array is still allocated, but not accessible. (Memory leak) CSC 143I 11 Destructors A class may have exactly one destructor. The destructor is automatically executed for each object when that object is about to be destroyed The destructor should do any cleanup needed before the object vanishes, including releasing dynamically allocated storage used by the object Destructor name is ~ClassName Destructor for IntLists (in intlist.cpp): // destructor IntList::~IntList( ) { CSC 143I 12

List Operations size and ismember present no surprises // = # items in this list int IntList::size( ) const { return sz; // = n is in this list bool IntList::isMember(int n) const{ int k = 0; while (k<sz && n!=l[k]) return k<sz; Stream output (<<) is similar to previous versions. CSC 143I 13 this Pointer In a member function, references to member data are done via a pointer variable this, which is an implicit parameter to every member function. this is automatically initialized when a member function is called, and can be used explicitly if desired. // = n is in this list bool IntList::isMember(int n) const{ int k = 0; while(k < this->sz && n!= this->l[k]) return k < this->sz; CSC 143I 14 Function add Function add (cont) add is easy if there is room in the array for the new int value. // add n to this IntList IntList& IntList::add(int n){ if (sz == arraysz) { // array is full, make it bigger // add n at end of array L[sz] = n; sz++; If the array is full, we allocate a new one twice as large and copy the existing values to it. if (sz == arraysz) { // array is full; double its size arraysz = 2 * arraysz; int * new newl[k] = L[k]; delete [ ] L; L = newl; // add n at end of array L[sz] = n; sz++; CSC 143I 15 CSC 143I 16 operator+ To compute the sum of two lists, construct a new list large enough to hold both IntLists. //=new list with contents of *this and t const IntList Intlist::operator+ (const IntList &t) const { IntList ans(arraysz + t.arraysz); int j, k; for (k=0; k<sz; k++) // copy *this ans.l[k]=l[k]; for (j=0; j<t.sz; j++) { // copy t ans.l[k] = t.l[j]; ans.sz = sz + t.sz; return ans; Are we done? Almost. But suppose we have the following two IntLists. CSC 143I 17 CSC 143I 18 p 8 4 q 5 3 11121314 202122 What happens if we execute assignment p=q;?

Problems after p=q; Aliasing: p.l and q.l refer to the same array Changes to one will affect the other Information about array sizes and number of IntList elements in p and q can become inconsistent. Shallow vs Deep Copy The problem is that the default assignment operator only copies the top-level data in the object, and does not clone any data pointed to from there. This is known as a shallow copy. Memory leak: What happened to the array with IntList p s old data? Multiple destructor problem. When p and q are eventually deleted, IntList::~IntList will be called twice, which will attempt to delete the (one) What we want is a deep copy, which copies the entire object, including any dynamic data it references. Solution: Redefine assignment for IntLists. array twice. CSC 143I 19 CSC 143I 20 Assignment: operator= First implementation // assign contents of rhs to this IntList void IntList::operator= (const IntList& rhs){ // New array with the size of rhs.l arraysz = rhs.arraysz; // copy values to this array sz = rhs.sz; L[k] = rhs.l[k]; Are we done? (2) Close. Problem 1: What happens if we execute p=p;? Problem 2: C/C++ allows multiple assignments. The meaning of w = x = y = z; is supposed to be w = (x = (y = z)); So operator= needs to return a reference to the value assigned so it can be used as the source for further assignments. CSC 143I 21 CSC 143I 22 Fixing operator= Solution 1: Check to see if this IntSet is the same as the one on the right side of the assignment. void IntList::operator=(const IntList &rhs){ if (this == &rhs) return; //nothing done Solution 2: operator= should return a reference to the object it has just updated. // update this object // return reference to new value CSC 143I 23 Revised operator= // assign contents of rhs to // this IntList IntList & IntList::operator= (const IntList &rhs){ //exit if attempting to assign to self if (this == &rhs) // New array with the size of rhs.l arraysz = rhs.arraysz; CSC 143I 24

Revised operator= (cont) Are we done? (3) // copy values to this array sz = rhs.sz; L[k] = rhs.l[k]; // return reference to result Much closer Last wrinkle. What if we declare and initialize an IntList like L2 below? IntList L1; L1.add(10); IntList L2 = L1; Or suppose we have an IntList value parameter void f(intlist L3) { CSC 143I 25 CSC 143I 26 Are we done? (3) (cont) Or suppose a function returns an (anonymous) IntList created by copying a local variable. IntList g() { IntList result; //calculate answer and store in result return result; In these situations, we re creating a new, neverinitialized IntList, not updating one that already has a value. So operator= isn t quite right. CSC 143I 27 Copy Constructor A constructor with a const & parameter of the same class. Executed whenever a new, never initialized object is created with a specified initial value. // copy constructor IntList::IntList(const IntList &val){ // allocate array same size as // initial value, then copy data arraysz = val.arraysz; sz = val.sz; L[k] = val.l[k]; CSC 143I 28 Defining a New C++ Type A complete C++ class should contain the following members Constructor(s) - including one with no parameters (null constructor) Copy constructor Destructor Assignment (operator=) Instances of such classes will work like variables of any built-in type (including declaration, assignment, and use as function parameters) Additional operations and redefinitions of others (operator==, for example) will also usually be needed/desired, depending on the application CSC 143I 29 Are we done? (4) Yes! * *: what if we can't allocate any space when creating an IntList? CSC 143I 30