1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems.

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

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Main Index Contents 11 Main Index Contents Pointer Illustration Pointer Illustration Vertical / Horizontal View. Vertical / Horizontal View. Data Addresses.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Main Index Contents 11 Main Index Contents Pointer Illustration Pointer Illustration Vertical / Horizontal View. Vertical / Horizontal View. Data Addresses.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 10: Pointers.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
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.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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.
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.
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.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified by use by the MSU CMPS Dept. Chapter 10:
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Pointers OVERVIEW.
1 Data Structures and Algorithms Pointers and Dynamic Data.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
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.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CS 1704 Introduction to Data Structures and Software Engineering.
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
Lecture 10: 2/17/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
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.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
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.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, //
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
Chapter 14 Dynamic Data and Linked Lists
Standard Version of Starting Out with C++, 4th Edition
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9: Pointers.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 9: Pointers.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15-3 Pointers, Dynamic Data, and Reference Types
CS148 Introduction to Programming II
9-10 Classes: A Deeper Look.
Standard Version of Starting Out with C++, 4th Edition
9-10 Classes: A Deeper Look.
Presentation transcript:

1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems

2 int* ptr = new int; *ptr = 3; ptr = new int; // Changes value of ptr *ptr = 4; What happens here? 3 ptr 3 ptr 4

3 Inaccessible Object An inaccessible object is an unnamed object created by operator new that a programmer has left without a pointer to it. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; How else can an object become inaccessible? 8 ptr -5 ptr2

4 Making an Object Inaccessible int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; //Here the 8 becomes // inaccessible 8 ptr -5 ptr2 8 ptr -5 ptr2

5 Memory Leak A memory leak is the loss of available memory space that occurs when dynamic data is allocated but never deallocated

6 A dangling pointer is a pointer that points to dynamic memory that has been deallocated int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; A Dangling Pointer 8 ptr -5 ptr2 For example,

7 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr2 = NULL; Leaving a Dangling Pointer 8 ptr -5 ptr2 8 ptr NULL ptr2

8 Reference Types int& intRef; Reference Type Declaration DataType& Vaiable; DataType &Variable, &Variable, …;

9 Use reference variable Use reference variable as alias int someInt; int& intRef = someInt; intRef = 1; void DatePrint(Date& someDate) { someDate.Print(); }

10 The difference of using a reference variable and using a pointer variable Using a Reference Variable int gamma = 26; int& intRef = gamma; // Assert: intRef points to gamma intRef = 35; // Assert: gamma == 35 intRef = intRef + 3; // Assert: gamma == 38 Using a Pointer Variable int gamma = 26; int* intPtr = γ // Assert: intPtr points to gamma *intPtr = 35; // Assert: gamma == 35 *intPtr = *intPtr + 3; // Assert: gamma == 38

11 Reference Variables are Constant Pointers Reference variables cannot be reassigned after initialization Initialization means: Explicit initialization in a declaration Implicit initialization by passing an argument to a parameter Implicit initialization by returning a function value

12 The use of reference variables The following code fails: void Swap(float x, float y) { float temp = x; x = y; y = temp; } Swap(alpha, beta);

13 The use of reference variables The following code uses pointer variables: void Swap(float* x, float* y) { float temp = *x; *x = *y; *y = temp; } Swap(&alpha, &beta);

14 The use of reference variables The following code uses reference variables: void Swap(float& x, float& y) { float temp = x; x = y; y = temp; } Swap(alpha, beta);

15 The usage of Ampersand (&) PositionUsageMeaning Prefix&VariableAddress of operation InfixExpression & Expression Bitwise AND operation InfixExpression && Expression Logical AND operation PostfixDataType&DataType (specifically, a reference type) Exception: To declare two variables of reference types, the & must be attached to each variable name: Int &var1, &var2;

16 // 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

17 // Specification file continued ~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 17

18 // Specification file continued 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; }; 18

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

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

21 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; } 21

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

23 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; } 23

24 ? ? 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

25 ? -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

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

27 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

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

29 The End of Chapter 15 Part 2