1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, //

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.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Class and Objects.
Main Index Contents 11 Main Index Contents Pointer Illustration Pointer Illustration Vertical / Horizontal View. Vertical / Horizontal View. Data Addresses.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 13: Pointers, Classes, Lists, and Virtual Functions.
Dynamically Allocated Arrays May 2, Quiz 5 Today.
Copy Constructors Shallow Copy: –The data members of one object are copied into the data members of another object without taking any dynamic memory pointed.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
1 Class Constructors a class constructor is a member function whose purpose is to initialize the private data members of a class object the name of a constructor.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory Allocation 9.8.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
1 Data Structures and Algorithms Pointers and Dynamic Data.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
More C++ Features True object initialisation
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
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:
Chapter 9 Classes: A Deeper Look, Part I Part II.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
1 Final Exam Tues 3/16/10 (2-3:50) (Same classroom) Old Textbook - Chapters 11-16, 18 Focus is on 15, 16 and 18 Final Exam Tues 3/16/10 (2-3:50) (Same.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
What happens... l When a function is called that uses pass by value for a class object like our dynamically linked stack? StackType MakeEmpty Pop Push.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
1 Data Structures and Algorithms Stacks and Queues.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
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.
Dynamic Memory Review l what is static, automatic, dynamic variables? Why are dynamic(ally allocated) variables needed l what is program stack? Function.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Learners Support Publications Constructors and Destructors.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
POINTERS AND MEMORY ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
Chapter 14 Dynamic Data and Linked Lists
Constructors and Destructors
Programming with ANSI C ++
Class: Special Topics Copy Constructors Static members Friends this
Memberwise Assignment / Initialization
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
Chapter 15-3 Pointers, Dynamic Data, and Reference Types
CS148 Introduction to Programming II
9-10 Classes: A Deeper Look.
Class: Special Topics 2 For classes using memory allocation
9-10 Classes: A Deeper Look.
Presentation transcript:

1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, // allows aggregate array copying and initialization. class DynArray { public: DynArray( /* in */ int arrSize ); // Constructor. // PRE: arrSize is assigned // POST: IF arrSize >= 1 && enough memory THEN // Array of size arrSize is created with // all elements == 0 ELSE error message. DynArray( const DynArray& otherArr ); // Copy constructor. // POST: this DynArray is a deep copy of otherArr // Is implicitly called for initialization. 1

2 // SPECIFICATION FILE continued (dynarray.h) ~DynArray( ); // Destructor. // POST: Memory for dynamic array deallocated. int ValueAt ( /* in */ int i ) const; // PRE: i is assigned. // POST: IF 0 <= i < size of this array THEN // FCTVAL == value of array element at index i // ELSE error message. void Store ( /* in */ int val, /* in */ int i ) // PRE: val and i are assigned // POST: IF 0 <= i < size of this array THEN // val is stored in array element i // ELSE error message. 2

3 // SPECIFICATION FILE continued (dynarray.h) void CopyFrom ( /* in */ DynArray otherArr); // POST: IF enough memory THEN // new array created (as deep copy) // with size and contents // same as otherArr // ELSE error message. private: int* arr ; int size ; }; 3

4 class DynArray ? ? Private data: size 5 arr 6000 Free store 6000 DynArray Store ValueAt DynArray ~DynArray CopyFrom

5 DynArray beta(5); //constructor ? ? ? Private data: size 5 arr 2000 Free store 2000 DynArray Store ValueAt DynArray ~DynArray CopyFrom beta

6 DynArray::DynArray( /* in */ int arrSize ) // Constructor. // PRE: arrSize is assigned // POST: IF arrSize >= 1 && enough memory THEN // Array of size arrSize is created with // all elements == 0 ELSE error message. { int i; if ( arrSize < 1 ) { cerr << “DynArray constructor - invalid size: “ << arrSize << endl; exit(1); } arr = new int[arrSize] ; // allocate memory size = arrSize; for (i = 0; i < size; i++) arr[i] = 0; } 6

7 beta.Store(75, 2); ? 75 ? ? Private data: size 5 arr 2000 Free store 2000 DynArray Store ValueAt DynArray ~DynArray CopyFrom beta

8 void DynArray::Store ( /* in */ int val, /* in */ int i ) // PRE: val and i are assigned // POST: IF 0 <= i < size of this array THEN // arr[i] == val // ELSE error message. { if ( i = size ) { cerr << “Store - invalid index : “ << i << endl; exit(1) ; } arr[i] = val ; } 8

9 ? ? Private: size 4 arr Private: size 5 arr ? 75 ? ? gamma beta DynArray gamma(4);//constructor DynArray Store ValueAt DynArray ~DynArray CopyFrom DynArray Store ValueAt DynArray ~DynArray CopyFrom

10 ? -8 ? Private: size 4 arr Private: size 5 arr ? 75 ? ? gamma beta gamma.Store(-8,2); DynArray Store ValueAt DynArray ~DynArray CopyFrom DynArray Store ValueAt DynArray ~DynArray CopyFrom

11 int DynArray::ValueAt ( /* in */ int i ) const // PRE: i is assigned. // POST: IF 0 <= i < size THEN // FCTVAL == arr[i] // ELSE halt with error message. { if ( i = size ) { cerr << “ValueAt - invalid index : “ << i << endl; exit(1) ; } return arr[i]; } 11

12 Why is a destructor needed? When a DynArray class variable goes out of scope, the memory space for data members size and pointer arr is deallocated. But the dynamic array that arr points to is not automatically deallocated. A class destructor is used to deallocate the dynamic memory pointed to by the data member.

13 DynArray::~DynArray( ); // Destructor. // POST: Memory for dynamic array deallocated. { delete [ ] arr ; } 13 class DynArray Destructor

14 Copy Constructor l An overloaded constructor l When an object is passed to a function, a bitwise (exact) copy of that object is made and given to the function. l If the object contains a pointer to allocated memory, the copy will point to the memory as does the original object.

15 Copy Constructor l If the copy makes a change to the contents of this memory, it will be changed for the original object too. l Also, when the function terminates, the copy will be destroyed, causing its destructor to be called. l That can free dynamically allocated memory, used by the original object as well.

16 What happens... l When a function is called that uses pass by value for a class object of DynArray type? ? 75 ? ? Private: size 5 arr DynArray Store ValueAt DynArray ~DynArray CopyFrom

17 // FUNCTION CODE void SomeFunc( DynArray someArr ) // Uses pass by value {. } 17 Passing a Class Object by Value

18 By default, Pass-by-value makes a shallow copy DynArray beta(5); // CLIENT CODE. SomeFunc( beta ); // function call beta someArr ? 75 ? ? 2000 DynArray. Private: size 5 arr 2000 DynArray. Private: size 5 arr 2000 shallow copy

19 // FUNCTION CODE void SomeFunc( DynArray someArr ) // Uses pass by value { someArr.Store(290, 2);. } WHAT HAPPENS IN THE SHALLOW COPY SCENARIO? 19 Suppose SomeFunc calls Store

20 DynArray beta(5); // CLIENT CODE. SomeFunc( beta); beta.arr[2] has changed beta someArr ? 290 ? ? 2000 DynArray. Private: size 5 arr 2000 DynArray. Private: size 5 arr 2000 shallow copy

21 beta.arr[2] has changed NOTICE THAT NOT JUST FOR THE SHALLOW COPY, BUT ALSO FOR ARGUMENT beta, THE DYNAMIC DATA HAS CHANGED! beta someArr ? 290 ? ? 2000 DynArray. Private: size 5 arr 2000 DynArray. Private: size 5 arr 2000 shallow copy

22 CONSTRUCTOR COPY CONSTRUCTOR DESTRUCTOR Classes with Data Member Pointers Need

23 Shallow Copy vs. Deep Copy l a shallow copy copies only the class data members, and does not make a copy of any pointed-to data l a deep copy copies not only the class data members, but also makes a separate stored copy of any pointed-to data

24 What’s the difference? l a shallow copy shares the pointed to dynamic data with the original class object l a deep copy makes its own copy of the pointed to dynamic data at different locations than the original class object

25 ? 75 ? ? 4000 DynArray. Private: size 5 arr 4000 beta someArr deep copy ? 75 ? ? 2000 DynArray. Private: size 5 arr 2000 Making a (Separate) Deep Copy

26 Assignment and Initialization l In both cases the value of one object is given to another. l Copy constructor only applies to initializations.

27 Initialization of Class Objects l Initialization can occur three ways: n an object is used to initialize another in a declaration statement, n passing an object argument by value to a function, n returning a temporary object as the return value of a function, l by default, C++ uses shallow copies for these initializations

28 default copy constructor l C++ automatically provides a default copy constructor that simply duplicates the object. l It is possible to specify precisely how one object will initialize another by defining a copy constructor. l Copy constructor do not affect assignment operations.

29 Common form of Copy Constructor classname(const classname &obj) {... } Here obj is a reference to an object that is being used to initialize another object. Time t1=t2; // explicitly initializing t1 func1(t2); // t2 passed as a parameter t2=func1(); // t2 receiving a returned object In the first two cases, a reference to t2 would be passed to the copy constructor. In the third, a reference to the object returned by funct2() is passed to the copy constructor.

30 As a result... l when a class has a data member pointer to dynamically allocated data, you should write what is called a copy constructor l the copy constructor is implicitly called in initialization situations and makes a deep copy of the dynamic data in a different memory location

31 More about Copy Constructors l when there is a copy constructor provided for a class, the copy constructor is used to make copies for pass by value l you do not call the copy constructor l like other constructors, it has no return type l because the copy constructor properly defines pass by value for your class, it must use pass by reference in its definition

32 Copy Constructor l copy constructor is a special member function of a class that is implicitly called in these 3 situations: n passing object parameters by value n initializing an object variable in its declaration n returning an object as the return value of a function

33 ? 75 ? ? Private: size 5 arr Private: size 5 arr ? 75 ? ? beta someArr SomeFunc(beta); // copy-constructor // beta passed by value DEEP COPY DynArray Store ValueAt DynArray ~DynArray CopyFrom DynArray Store ValueAt DynArray ~DynArray CopyFrom

34 DynArray::DynArray( const DynArray& otherArr ) // Copy constructor // Implicitly called for deep copy in initializations. // POST: If room on free store THEN // new array of size otherArr.size is created // on free store && arr == its base address // && size == otherArr.size // && arr[0..size-1] == otherArr.arr[0..size-1] // ELSE error message. { int i ; size = otherArr.size ; arr = new int[size] ; // allocate memory for copy for ( i = 0; i< size ; i++ ) arr[i] = otherArr.arr[i] ; // copies array } 34

35 What about the assignment operator? l the default method used for assignment of class objects makes a shallow copy l if your class has a data member pointer to dynamic data, you should write a member function to create a deep copy of the dynamic data

36 gamma.CopyFrom(beta); ? 75 ? ? Private: size 5 arr Private: size 5 arr ? 75 ? ? gamma beta DEEP COPY DynArray Store ValueAt DynArray ~DynArray CopyFrom DynArray Store ValueAt DynArray ~DynArray CopyFrom

37 void DynArray::CopyFrom ( /* in */ DynArray otherArr ) // Creates a deep copy of otherArr. // POST: Array pointed to by deallocated // && IF room on free store // THEN new array is created on free store // && arr == its base address // && size == otherArr.size // && arr[0..size-1] == otherArr[0..size-1] // ELSE halts with error message. { int i ; delete [ ] arr ;// delete current array size = otherArr.size ; arr = new int [size] ;// allocate new array for ( i = 0; i< size ; i++ ) // deep copy array arr[i] = otherArr.arr[i] ; } 37