25
Beginning C++ Through Game Programming, Second Edition by Michael Dawson

Beginning C++ Through Game Programming, Second Edition

  • Upload
    marvin

  • View
    74

  • Download
    5

Embed Size (px)

DESCRIPTION

Beginning C++ Through Game Programming, Second Edition. by Michael Dawson. Chapter 7. Pointers: Tic-Tac-Toe 2.0. Objectives. Declare and initialize pointers Dereference pointers Use constants and pointers Pass and return pointers Work with pointers and arrays. Pointer Basics. - PowerPoint PPT Presentation

Citation preview

Page 9: Beginning C++ Through Game Programming, Second Edition

Dereferencing Pointers• Dereference a pointer to access the object to which it pointscout << *pScore;

• Sends cout value that pScore points to • Don’t dereference a null pointer• Don't forget to dereference a pointerpScore += 500;

• Adds 500 to the address stored in pScore, not to the value to which pScore originally pointed

Page 16: Beginning C++ Through Game Programming, Second Edition

Example: Passing Pointers• When you pass a pointer, you pass only the address of an object• Can be quite efficient, especially if you’re working with large objectsvoid Swap(int* const pX, int* const pY) • pX and pY are constant pointers and will each accept a memory address • Must pass addresses when passing to pointer parameters Swap(&myScore, &yourScore);

Page 19: Beginning C++ Through Game Programming, Second Edition

Assignments and Returned Pointers

• Assign the returned pointer to a pointer that points to an object of the same typestring* pStr = func();

• Efficient; assigning a pointer to a pointer, no string object is copied.string str = func();

• Copies the string object that the returned pointers point to• For large objects, could be an expensive operation

Page 24: Beginning C++ Through Game Programming, Second Edition

Summary (cont.)• If you assign 0 to a pointer, the pointer is called a null pointer• To get the address of a variable, put the address of the operator (&) before the variable name• Unlike references, you can reassign pointers• Dereference a pointer to access the object it points to with *, the dereference operator• Use the -> operator with pointers for a more readable way to access object data members and member functions

Page 25: Beginning C++ Through Game Programming, Second Edition

Summary (cont.)

• A constant pointer can only point to the object it was initialized to point to • Can't use a pointer to a constant to change the value to which it points• A constant pointer to a constant can only point to the value it was initialized to point to, and it can’t be used to change that value • You can pass pointers for efficiency or to provide direct access to an object• A dangling pointer is a pointer to an invalid memory address • Dereferencing a dangling pointer can lead to disastrous results• You can return a pointer from a function, but be careful not to return a dangling pointer