11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: Taking a First Look at C++ Pointers 117n = 0lower = 0Storing 13.0 into the location &nThe final results are:upper = 1076494336n = 0lower = 0Press any key to continue . . .The house equivalent goes something like this:House* houseAddress = &”123 Main Street”;Hotel* hotelAddress;hotelAddress = (Hotel*)houseAddress;*hotelAddress = TheRitz;houseAddress is initialized to point to my house. The variable hotelAddressis a pointer to a hotel. Now, the house address is cast into the address of ahotel and saved off into the variable hotelAddress. Finally, TheRitz isplopped down on top of my house. Because TheRitz is slightly bigger thanmy house (okay, a lot bigger than my house), it isn’t surprising that TheRitzwipes out my neighbors’ houses as well.The type of pointer saves the programmer from stuffing an object into aspace that is too big or too small. The assignment *pintVar = 100.0; actuallycauses no problem — because C++ knows that pintVar points to an int,C++ knows to demote the 100.0 to an int before making the assignment.Passing Pointers to FunctionsOne of the uses of pointer variables is in passing arguments to functions. Tounderstand why this is important, you need to understand how argumentsare passed to a function.Passing by valueYou may have noticed that it is not normally possible to change the value of avariable passed to a function from within the function. Consider the followingexample code segment:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!