c programming program design including data structures second edition n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
C++ Programming: Program Design Including Data Structures, Second Edition PowerPoint Presentation
Download Presentation
C++ Programming: Program Design Including Data Structures, Second Edition

play fullscreen
1 / 122

C++ Programming: Program Design Including Data Structures, Second Edition

124 Views Download Presentation
Download Presentation

C++ Programming: Program Design Including Data Structures, Second Edition

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. C++ Programming: Program Design Including Data Structures, Second Edition Chapter 13: Pointers, Classes, Lists, and Virtual Functions

  2. Objectives In this chapter you will: • Learn about the pointer data type and pointer variables • Explore how to declare and manipulate pointer variables • Learn about the address of operator and the dereferencing operator • Discover dynamic variables C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  3. Objectives • Explore how to use the newanddeleteoperators to manipulate dynamic variables • Learn about pointer arithmetic • Discover dynamic arrays • Become aware of theshallow and deep copies of data • Discover the peculiarities of classes with pointer data members C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  4. Objectives • Explore how dynamic arrays are used to process lists • Learn about virtual functions • Examine the relationship between the address of operator and classes C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  5. Pointer Variables • Pointer variable: the content is a memory address • Declaring Pointer Variables: dataType *identifier; int *p; char *ch; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  6. Pointer Variables (continued) • These statements are equivalent • int *p; • int* p; • int * p; • The character * can appear anywhere between type name and variable name int* p, q; • Only p is the pointer variable, not q • Here q is an int variable C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  7. Pointer Variables (continued) • To avoid confusion, attach the character * to the variable name int *p, q; • The following statement declares both p and q to be pointer variables of the type int int *p, *q; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  8. 6000 ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ str [0] [1] [2] [3] [4] [5] [6] [7] Recall that . . . char str [ 8 ]; stris thebase addressof the array. We say str is a pointerbecause 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. expanded by J. Goetz, 2004

  9. 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; 2000 2002 2006 x number ch expanded by J. Goetz, 2004

  10. Address Of Operator (&) • The ampersand, &, is called the address of operator • Address of operator: unary operator that returns the address of its operand int x; int *p; p = &x; // returns the address of x, store the address of x in p // x and value of p refer to the same memory location C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  11. Obtaining Memory Addresses • the address of a non-array variable can be obtained by using theaddress-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; expanded by J. Goetz, 2004

  12. What is a pointer variable? • A pointer variableis a variablewhosevalue is the addressof a location in memory. • to declarea pointer variable, you must specifythe 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 enum ColorType {RED, GREEN, BLUE}; ColorType color; ColorType* colorPtr; expanded by J. Goetz, 2004

  13. Using a Pointer Variable 2000 12 x 3000 2000 ptr int x; x = 12; int* ptr; ptr = &x; NOTE: Because ptr holds the address of x, we say that ptr “points to” x enum ColorType {RED, GREEN, BLUE}; ColorType color; ColorType* colorPtr = &color ; expanded by J. Goetz, 2004

  14. Dereferencing Operator (*) • C++ uses * as • the binary multiplication operator and • as a unary operator • When used as a unary operator, * • Called the dereferencing operator or indirection operator • Refers to the object to which its operand (that is, a pointer) points C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  15. Dereferencing Operator (*) int x = 25; int *p; p = &x; // store the address of x in p count << *p << endl; // prints 25 • *p refers to the object to whicha pointer ppoints C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  16. Unary operator * is the indirection (dereference) operator 2000 *ptr 12 x 3000 2000 ptr int x; x = 12; int* ptr; ptr = &x; cout << *ptr; NOTE:The valuepointed to byptr is denoted by *ptr expanded by J. Goetz, 2004

  17. Using the Dereference Operator int x; x = 12; int* ptr; ptr = &x; *ptr = 5; // changes the value // at address ptr to 5 2000 12 5 x 3000 2000 ptr expanded by J. Goetz, 2004

  18. Another Example 4000 *q A Z ch 5000 6000 4000 4000 q p char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; // the &ch has value 4000 // now p and q both point to ch expanded by J. Goetz, 2004

  19. Using a Pointer to Access the Elements of a String 3000 char msg[ ] = “Hello”; ‘M’ ‘a’ 3001 char* ptr; 3000 ptr = msg; // recall that msg == &msg[ 0 ] *ptr = ‘M’ ; ptr++; // increments the address in ptr *ptr = ‘a’; ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ ptr expanded by J. Goetz, 2004

  20. 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; } 20 expanded by J. Goetz, 2004

  21. floating address float double long double pointer reference C++ Data Types simple structured integral enum array struct union class char short int long bool C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  22. Classes, structs, and Pointer Variables • Pointers can be declared to classes and structs • To simplify the accessing of class orstructcomponents via a pointer, • C++ provides the member access operator arrow, -> • The syntax for accessing a class (struct) member using the operator -> is: pointerVariableName->classMemberName C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  23. Using a Pointer to Access the Elements Syntax: • PointerVariable -> MemberName or • (* PointerVariable).MemberName • TimeType startTime(8, 30, 0); TimeType* timePtr; (*timePtr).Increment(); // or timePtr ->Increment(); • TimeType* myArray[20] (*myArray[4] ).Increment(); // or myArray[4]->Increment(); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  24. Some C++ Pointer Operations Precedence Higher->Select member of class pointed to Unary: ++ -- ! * new delete Increment, Decrement, NOT, Dereference, Allocate, Deallocate + - Add Subtract < <= > >= Relational operators == != Tests for equality, inequality Lower = Assignment 24 expanded by J. Goetz, 2004

  25. Initializing Pointer Variables • C++ does not automatically initialize variables • Pointer variables can be initialized using the constant value 0, called the “null pointer” denoted byNULLin header file cstddef p.1474. The following two statements are equivalent:p = NULL; // predefined constant p = 0; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  26. Initializing Pointer Variables 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 } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  27. 3 Kinds of Program Data • STATIC DATA:memory allocation exists throughout execution of program 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 expanded by J. Goetz, 2004

  28. 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. expanded by J. Goetz, 2004

  29. Dynamic Variables • Dynamic variables: created during execution • using pointers • Two operators, new and delete, • to create and destroy dynamic variables • new and delete are reserved words C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  30. Operator new • The syntax for new: new dataType; //to allocate a single variable e.g. p = newint; new dataType [intExp]; //to allocate an array of variables e.g. p = newchar[5]; where intExp is any expression evaluating to a positive integer • If memory is available, in an area called the heap (or free store) newallocates memory of the designated type and returns a pointer to it. • Otherwise, program terminates with error message. • Allocated memory is uninitialized • The dynamically allocated object exists until the delete operator destroys it. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  31. Dynamically Allocated Data 2000 ptr char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; expanded by J. Goetz, 2004

  32. Dynamically Allocated Data p.710 2000 ptr char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: The statement stores the address of the allocated memory in ptr expanded by J. Goetz, 2004

  33. Dynamically Allocated Data 2000 ptr ‘B’ char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name expanded by J. Goetz, 2004

  34. Dynamically Allocated Data 2000 ptr NOTE: the delete operator 1.deallocates the memory pointed to by ptr and 2. pointed- to variable *ptr is deleted (dynamic data is deleted) char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; ? expanded by J. Goetz, 2004

  35. Operator delete • deletedestroys dynamic variables • The syntax of delete has two forms (statements): delete pointer; //to destroy a single dynamic variable delete [] pointer; //to destroy a dynamically //created array • Operator delete returnsto thefree store memory which was previously allocated at run-time by operator new • it deletes the pointed-to variable (dereferenced variable) • The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned (undefined). C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  36. Operator delete • The syntax of delete has two forms (statements): delete pointer; //to destroy a single dynamic variable delete [] pointer; //to destroy a dynamically //created array • The statements delete p; delete [] name; deallocate memory referenced by the pointers p and name • Square brackets are used with delete to deallocate a dynamically allocated array. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  37. What happens here? 3 ptr int* ptr = new int; *ptr = 3; ptr = new int; // changes value of ptr *ptr = 4; // here the 3 becomes inaccessible 3 ptr 4 expanded by J. Goetz, 2004

  38. 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 expanded by J. Goetz, 2004

  39. Making an Object Inaccessible 8 ptr -5 ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2;// here the 8 becomes inaccessible 8 ptr -5 ptr2 expanded by J. Goetz, 2004

  40. Memory Leak • A memory leak is the loss of available memory space • that occurs when dynamic data is allocatedbutnever deallocated. expanded by J. Goetz, 2004

  41. 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; 8 ptr -5 ptr2 FOR EXAMPLE, expanded by J. Goetz, 2004

  42. Leaving a Dangling Pointer 8 ptr -5 ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2;// here the 8 becomes inaccessible delete ptr2; // ptr is left dangling !!! ptr2 = NULL; 8 ptr NULL ptr2 expanded by J. Goetz, 2004

  43. Operations on Pointer Variables • Assignment: value of one pointer variable can be assigned to another pointer of same type • Relational operations: two pointer variables of same type can be compared for equality, etc. • Some limited arithmetic operations: • Integervalues can be added and subtracted from a pointer variable • Value of one pointer variable can be subtracted from another pointer variable C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  44. Some C++ Pointer Operations • int arr[10]; int* ptr; the assignmentstatement ptr = arr; has the effect as ptr = &arr[0]; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  45. Some C++ Pointer Operations • The logical NOT operator can be used to test the null pointer: if (!ptr) //in spite of ptr is a pointer expression, not a Boolean expression DoSomething(); • The same but preferable: if (ptr == NULL) DoSomething(); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  46. Some C++ Pointer Operations • To testpointers: int *intPtr1, *intPtr2; if (intPtr1 == intPtr2) • To test the integers that intPtr1, intPtr2 point to: if (*intPtr1 == *intPtr2) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  47. Operations on Pointer Variables • When an integer is added to a pointer variable • Value of pointer is incremented by integer times the size of the memory that the pointer points to • If ptr points some element of an array (int array[]), then ptr + 7 points the array element that is seventhbeyond the one currently pointed to by ptr (regardless of the size in bytes of each array element) • When an integer is subtracted from a pointer variable • Value of pointer variable is decremented by the integer times the size of the memory to which the pointer is pointing C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  48. Dynamic Arrays • Dynamic array: array created during execution • Use the second form of the new operator to create a dynamic array • The statement • p = new int[10]; • allocates 10 contiguous memory locations, each of the type int, and storesthe address of the first memory location into p C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  49. 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 6000 6000 ptr expanded by J. Goetz, 2004

  50. Dynamic Array Allocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; // a pointer can be subscripted or ptr++; *ptr = ‘u’; cout << ptr[ 2] ; ‘u’ 6000 ‘B’ ‘y’ ‘e’ ‘\0’ ptr 6000 expanded by J. Goetz, 2004