CS 105: C++
Quiz 11 Requirements
C++: Chapter 7, 8

  1. C already had mechanisms for allocating and deallocating memory (malloc and free).  What are the C++ replacements for these, and what useful things do they do that malloc and free do not do?

  2. Be able to write (with correct syntax) simple C++ code to allocate and deallocate memory.  For example, can you write the C++ equivalents of the following statements?

    float *fp = malloc(sizeof(float));
    free(fp);

  3. Be able to write (with correct syntax) simple C++ code to allocate and deallocate memory for an array.  For example, can you write the C++ equivalents of the following statements?

    float *fa = malloc(sizeof(float) * 10);
    free(fa);

  4. Be able to allocate and deallocate memory for a class instance in C++.  For example, can you complete the following statement so that bp points to a dynamically allocated instance of class Bar?  Can you write code to deallocate that instance?

    Bar *bp = ________________ ;

  5. References in C++ are a very useful variation on pointers.  Learn how to use them, including the rules for their syntax.  For example, can you rewrite the following code to use references instead of pointers?

    #include <iostream>
    using namespace std;

    void plus_5(int *ip) {
    *ip = *ip + 5;
    }

    int main() {
    int n = 3;
    plus_5(&n);
    cout << n << '\n';
    }
  6. It's legal for a base-class pointer to point to an object of a derived class.  Is the same true for references?  (I.e., can a base-class reference refer to an object of a derived class?)

  7. What's wrong with the following function?

    int& foo() {
    int n;

    n = 10 / 2;
    return n;
    }
  8. If n were declared as static in the function above, would there still be a problem?




Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.