Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 287

9


Workshop ............................................................................................................


The Workshop contains quiz questions to help solidify your understanding of the mater-
ial covered and exercises to provide you with experience in using what you’ve learned.
Try to answer the quiz and exercise questions before checking the answers in Appendix
D, and be certain you understand the answers before going to tomorrow’s lesson.

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



  1. What is the difference between a reference and a pointer?

  2. When must you use a pointer rather than a reference?

  3. What does newreturn if there is insufficient memory to make your new object?

  4. What is a constant reference?

  5. What is the difference between passing by reference and passing a reference?

  6. When declaring a reference, which is correct:
    a. int& myRef = myInt;
    b. int & myRef = myInt;
    c. int &myRef = myInt;


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



  1. Write a program that declares an int, a reference to an int, and a pointer to an
    int. Use the pointer and the reference to manipulate the value in the int.

  2. Write a program that declares a constant pointer to a constant integer. Initialize the
    pointer to an integer variable,varOne. Assign^6 to varOne. Use the pointer to
    assign 7 to varOne. Create a second integer variable,varTwo. Reassign the pointer
    to varTwo. Do not compile this exercise yet.

  3. Now compile the program in Exercise 2. What produces errors? What produces
    warnings?

  4. Write a program that produces a stray pointer.

  5. Fix the program from Exercise 4.

  6. Write a program that produces a memory leak.

  7. Fix the program from Exercise 6.
    8.BUG BUSTERS:What is wrong with this program?
    1: #include
    2: using namespace std;
    3: class CAT
    4: {
    5: public:

Free download pdf