Sams Teach Yourself C++ in 21 Days

(singke) #1
Answers 835

D


Day 9


Quiz ................................................................................................................


  1. A reference is an alias, and a pointer is a variable that holds an address. References
    cannot be null and cannot be assigned to.

  2. When you need to reassign what is pointed to, or when the pointer might be null.

  3. A null pointer (0).

  4. This is a shorthand way of saying a reference to a constant object.

  5. Passing byreference means not making a local copy. It can be accomplished by
    passing a reference or by passing a pointer.

  6. All three are correct; however, you should pick one style and then use it
    consistently.


Exercises ........................................................................................................


  1. The following is one possible answer:
    1: //Exercise 9.1 -
    2: #include
    3:
    4: int main()
    5: {
    6: int varOne = 1; // sets varOne to 1
    7: int& rVar = varOne;
    8: int pVar = &varOne;
    9: rVar = 5; // sets varOne to 5
    10:
    pVar = 7; // sets varOne to 7
    11:
    12: // All three of the following will print 7:
    13: std::cout << “variable: “ << varOne << std::endl;
    14: std::cout << “reference: “ << rVar << std::endl;
    15: std::cout << “pointer: “ << *pVar << std::endl;
    16:
    17: return 0;
    18: }

  2. The following is one possible answer.
    1: int main()
    2: {
    3: int varOne;
    4: const int const pVar = &varOne;
    5: varOne = 6;
    6:
    pVar = 7;
    7: int varTwo;
    8: pVar = &varTwo;
    9: return 0;
    10: }


32 0672327112_app_d.qxd 11/19/04 12:30 PM Page 835

Free download pdf