C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.

Slides:



Advertisements
Similar presentations
Informática II Prof. Dr. Gustavo Patiño MJ
Advertisements

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.
Chapter 4 ADT Sorted List.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
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.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
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.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
1 Data Structures and Algorithms Pointers and Dynamic Data.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
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.
Object-Oriented Programming in C++
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Pointer and Array Lists Chapter 3, Summary CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
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:
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
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.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
1 Final Exam 20 Questions Final Exam 20 Questions Multiple choice and some minimal programming will be required.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
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.
1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, //
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
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.
Chapter 14 Dynamic Data and Linked Lists
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Dynamically Allocated Memory
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15-3 Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
C++ Plus Data Structures
Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Presentation transcript:

C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on page 739)

2 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 because the value of str itself cannot be changed by assignment. It “points” to the memory location of a char. str [0] [1] [2] [3] [4] [5] [6] [7] ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ 6000

3 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 the address of the variable int x; float number; char ch; x number ch

4 Obtaining Memory Addresses the address of a non-array variable can be obtained by using the address-of operator & int x; float number; char ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number << endl; cout << “Address of ch is “ << &ch << endl;

5 What is a pointer variable? A pointer variable is a variable whose value is the address of a location in memory. to declare a pointer variable, you must specify the type of value that the pointer will point to,for example, int* ptr; // ptr will hold the address of an int char* q; // q will hold the address of a char

6 Using a Pointer Variable int x; x = 12; int* ptr; ptr = &x; NOTE: Because ptr holds the address of x, we say that ptr “points to” x x ptr

x ptr int x; x = 12; int* ptr; ptr = &x; cout << *ptr; NOTE: The value pointed to by ptr is denoted by *ptr Unary operator * is the indirection (deference) operator

8 int x; x = 12; int* ptr; ptr = &x; *ptr = 5; // changes the value // at address ptr to 5 Using the Dereference Operator x ptr

9 char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; // both pointers have the value 4000 // now p and q both point to ch Another Example 4000 A Z ch q p

Then 3001 ptr Using a Pointer to Access the Elements of a String ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ 3000 char msg[ ] = “Hello”; char* ptr; ptr = msg; // recall that msg == &msg[ 0 ] *ptr = ‘M’ ; // Changes 3000 to ‘M’ ptr++;// increments the address in ptr *ptr = ‘a’; // Changes 3001 to ‘a’

11 int StringLength ( /* in */ const char str[ ] ) // // Precondition: str is a null-terminated string // Postcondition: FCTVAL == length of str (not counting ‘\0’) // { char* p ; int count = 0; p = str; while ( *p != ‘\0’ ) { count++ ; p++ ; // increments the address p by sizeof char } return count; } 11

C++ Programming: From Problem Analysis to Program Design, Second Edition12 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double

Operator new Syntax new DataType new DataType [IntExpression] If memory is available, in an area called the heap (or free store) new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated. Otherwise, program terminates with error message. The dynamically allocated object exists until the delete operator destroys it. 13

14 The NULL Pointer There is a pointer constant 0 called the “null pointer” denoted by NULL in header file cstddef. But NULL is not memory address 0. NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this. while (ptr != NULL) {... // ok to use *ptr here }

15 3 Kinds of Program Data STATIC DATA: memory allocation exists throughout execution of program (global variables or by using the static keyword) static long currentSeed; AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete

16 Allocation of Memory STATIC ALLOCATION Static allocation is the allocation of memory space at compile time. DYNAMIC ALLOCATION Dynamic allocation is the allocation of memory space at run time by using operator new.

ptr Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr;

18 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr

19 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr ‘B’

20 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; 2000 ptr NOTE: delete deallocates the memory pointed to by ptr ?

Operator delete returns to the free store memory which was previously allocated at run-time by operator new. The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned. Using Operator delete 21

22 Dynamic Array Allocation char *ptr; // ptr is a pointer variable that // can hold the address of a char ptr = new char[ 5 ]; // dynamically, during run time, allocates // memory for a 5 character array // and stores the base address into ptr ptr 6000

23 Dynamic Array Allocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; // a pointer can be subscripted cout << ptr[ 2] ; ptr 6000 ‘B’ ‘y’ ‘e’ ‘\0’ ‘u’

Operator delete Syntax delete Pointer delete [ ] Pointer If the value of the pointer is 0 there is no effect. Otherwise, the object or array currently pointed to by Pointer is deallocated, and the value of Pointer is undefined. The memory is returned to the free store. Square brackets are used with delete to deallocate a dynamically allocated array. 24

25 Dynamic Array Deallocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; delete [ ] ptr; // deallocates array pointed to by ptr // ptr itself is not deallocated // the value of ptr is undefined. ptr ?

26 int* ptr = new int; *ptr = 3; ptr = new int; // changes value of ptr *ptr = 4; What happens here? 3 ptr 3 ptr 4

27 Inaccessible Object An inaccessible object is an unnamed object that was created by operator new and which 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

28 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

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

30 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,

31 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

C++ Programming: From Problem Analysis to Program Design, Second Edition32 Dynamic Array Class As an example of a class that uses dynamic storage, we will develop a dynamic array class Static arrays have the limitation that you must know the size at compile time: int scores[100]; Our class will allow dynamic allocation: // Calculate how many you need in scoreSize DynArray scores(scoreSize);

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

34 // 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.

35 // SPECIFICATION FILE continued (dynarray.h) ~DynArray( ); // Destructor. // POST: Memory for dynamic array deallocated. int ValueAt ( /* in */ int i ); // 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. 35

36 // 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 ; }; 36

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

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

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

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

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

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

43 int DynArray::ValueAt ( /* in */ int i ) // 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]; } 43

44 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.

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

46 What happens... 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

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

48 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

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

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

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

52 Initialization of Class Objects C++ defines initialization to mean − initialization in a variable declaration − passing an object argument by value − returning an object as the return value of a function by default, C++ uses shallow copies for these initializations

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

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

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

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

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

58 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

59 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

60 CONSTRUCTOR COPY CONSTRUCTOR DESTRUCTOR Classes with Data Member Pointers Need

C++ Programming: From Problem Analysis to Program Design, Second Edition61 The Constructor Automatically called when object created (object declaration) You can have multiple constructors that differ by type or number of passed parameters For objects that create dynamic data (and therefore use pointers) always have a constructor (if data not created in constructor, set the pointer to NULL) Objects for data structures will always need constructors to initialize the structure

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

C++ Programming: From Problem Analysis to Program Design, Second Edition63 Copy Constructor Needed when an object contains pointers to dynamic data, AND You need each object to have its own dynamic data

64 DynArray::DynArray( DynArray otherArr ) // Copy constructor (copy from otherArr) // 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 } 64

C++ Programming: From Problem Analysis to Program Design, Second Edition65 Destructor Automatically called when object goes out of scope Required when creating dynamic data in an object to free it Be careful when passing an object by value: On return from function, the destructor is called. If you did not have a copy constructor, it will delete the caller’s dynamic data

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

C++ Programming: From Problem Analysis to Program Design, Second Edition67 Copy From Another Object If the object has pointers: gamma = beta; Both objects point to the same dynamic data gamma dynamic data cannot be accessed (memory leak)

68 What about the assignment operator? the default method used for assignment of class objects makes a shallow copy 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

69 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

70 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] ; } 70

C++ Programming: From Problem Analysis to Program Design, Second Edition71 Functions and Pointers A pointer variable can be passed as a parameter Once you have a pointer, you can change the caller’s variable that it is pointing to (for example, arrays) void example(int* p) { *p = 0; // Changes caller’s variable // pointed to by p } A function can return a value of type pointer

C++ Programming: From Problem Analysis to Program Design, Second Edition72 Classes, structs, and Pointer Variables Pointers can be declared to classes and structs To simplify the accessing of class or struct components via a pointer −C++ provides the member access operator arrow, -> The syntax for accessing a class (struct) member using the operator -> is: pointerVariableName->classMemberName

73 // Student structure struct studentData { string name; float average; }; studentData student1; studentData* ptr; ptr = &student1; ptr->name = “Smith”; ptr->average = 92.3; 73 Pointer to a Structure. name. average “Smith” 92.3

74 Accessing Struct Data via a Pointer.name.average “Smith” 92.3 ptr.name.average (*ptr).name (old way- don’t use) ptr->name = “Jones”; ptr->average = 185/2; cout name; cout average; “Jones” 92.5

C++ Programming: From Problem Analysis to Program Design, Second Edition75 Pointer to a Class TimeType time1; TimeType* timeptr = &time1; timeptr->set(12,0,0); timeptr->increment(); … and so on Any public member function can be accessed via the pointer to its object

C++ Programming: From Problem Analysis to Program Design, Second Edition76 Pointer access to an array of objects // name is a class name* nameptr = new name[5]; string someNames[5]={"A","B","C","D","E"}; for (int i = 0;i < 5; i++) { nameptr[i].set(someNames[i]); }

C++ Programming: From Problem Analysis to Program Design, Second Edition77 What ptr[i]-> means name* namePtrList[5]; for (int j = 0;j < 5; j++) { namePtrList[j] = new name; namePtrList[j]->set(someNames[j]); }

C++ Programming: From Problem Analysis to Program Design, Second Edition78 Summary Pointer variables contain the addresses of other variables as their values Declare a pointer variable with an asterisk, *, between the data type and the variable & is called the address of operator & returns the address of its operand Unary operator * is the dereference operator

C++ Programming: From Problem Analysis to Program Design, Second Edition79 Summary The member access operator arrow, ->, accesses the component of an object pointed to by a pointer Dynamic variable: created during execution Operator new creates a dynamic variable Operator delete deallocates memory occupied by a dynamic variable Dynamic array: created during execution

C++ Programming: From Problem Analysis to Program Design, Second Edition80 Summary Shallow copy: two or more pointers of the same type point to the same memory Deep copy: two or more pointers of the same type have their own copies of the data