CS368 Fall 2009

Assignment 3

Due by the beginning of class on Wed. October 14

Please send e-mail questions to your TA: Maheswaran Venkatachalam, kvmakes@cs.wisc.edu

Print out your answers (or hand write them on paper) and turn them in.

  1. For each of the following declaration and initialization statements, identify what is declared as constant: the pointer variable's value, or what the pointer points to.
       const int * pX = &X;
    
       int * const pX = &X;
    
       int const * pX = &X;
    
  2. Which section (segment) of memory is a C++ programmer expected to manage?

    Give a brief definition of a memory leak.

    Why are memory leaks bad?
  3. What happens when the following function is executed?
    fcn() {
      int a=5;
    
      while(1)
      {
        int *p = new int();
        p = &a;
        a++;
      }
    }
    
  4. Briefly, why do we need the scope resolution operator (::)?
  5. Under what circumstances is the default destructor insufficient to prevent memory leaks?
  6. Does the following code compile without errors? Explain.
    #include <iostream>
    using namespace std;
    
    class myClass {
      private:
        int a;
      public:
        void updateval(int u) { a=a+u; }
    
        myClass(int v) { a = v; }
    
        void printval() {
          cout<<"\nThe updated value is : " << a << endl;
        }
    };
    
    int main(void) {
      myClass obj1; 
    
      obj1.updateval(2);
      obj1.printval();
      return 0;
    }
    
  7. Show how to modify this code such that data encapsuation is preserved.
    #include <iostream>
    using namespace std;
    
    class myClass {
      public:
        int a;
        void updateval(int u) { a=a+u; }
        void printval() {
          cout<<"\nThe updated value is : " << a << endl;
        }
    };
    
    int main(void) {
      myClass obj1; 
    
      obj1.a = 100;
      obj1.updateval(2);
      obj1.printval();
      return 0;
    }
    



© 2009 Karen Miller, with questions by Maheswaran Venkatachalam