CS 176, Introduction to Computer Science II

Summer 2001 - Quiz 2


  1. Given the following two perfectly legal C++ declarations
    class point {
      
        point(double X, double Y, double Z) {
          // whatever
          }
    
      private:
    
        double normalize(double x, double y) {
          // whatever
          }
    
        double x, y, z;
      };
    
    
    struct line {
      point end_point1, end_point2;
      };
    
    indicate whether each of the following statements are legal C++ or not, and explain why:
    1point pt1;
    2point pt2(1.0, 2.0, 3.0);
    3line ln1;
    4cout << "x = " << ln1.end_point1.x << endl;


    point pt1; - Not legal; this declaration uses the default constructor (the constructor with no parameters), which is not defined for point.

    point pt2(1.0, 2.0, 3.0); - Not legal; this declaration uses the constructor point(int, int, int), which exists but has the default class access permission private and so is unaccessible outside the class point.

    line ln1; - This one I screwed up. This is illegal because line doesn't have a default constructor. When I first wrote the quiz, this was legal because the class point had a default constructor.

    cout << "x = " << ln1.end_point1.x << endl;' - This is illegal because x is a private member variable in class point and cannot be accessed outside a point. The access privilege applied to an instance of a class has no effect on the access privileges applied to the members of the class.


  2. Write the code for the function having the prototype
    void uppercase_b(char str[]);
    
    that accepts as input the null-byte terminated array of characters str and changes every lower-case b into an upper case B only if the b is preceded by a (in either case) and followed by c (in either case). For example, abC should be changed to aBC but cba should remain unchanged.


    void uppercase_b(char str[]) {
    
      if (str[0] == '\0') return;
    
      for (int i = 1; str[i] != '\0'; i++)
        if ((tolower(str[i - 1]) == 'a') &&
            (str[i] == 'b') &&
            (tolower(str[i + 1]) == 'c')) str[i] = 'B';
      }
    


  3. A colleague of yours wrote the following program
    #include <iostream>
    
    static void set_to_five(int x) {
      x = 5;
      }
    
    int main() {
      int i;
      set_to_five(i);
      cout << "i = " << i << endl;
      }
    
    Your colleague was puzzled when the program successfully compiled and ran, but produced the following output:
    i = -4264572
    
    Recognizing your expertise as a C++ programmer, your colleague comes to you for an explanation. What do you say?


    Your colleague's problems apparently stems from the belief that changing a parameter inside a function will case the change to appear outside the function too. Only array parameters allow changes made inside a function to appear outside the function.



This page last modified on 3 July 2001.