Homework: Classes II

Consider the following nonsense class:

   class A
   {
   public:
      A();
      A(int A);
      void f();
      void g();
      int h();
      void k();
   private:
     int n;
   };
   A::A()
   {
     n = 0;
   }
   A::A(int a)
   {
     n = a;
   }
   void A::f()
   {
     n++;
   }
   void A::g()
   {
      f();
      n = 2 * n;
      f();
   }
   int A::h()
   {
      return n;
   }
   void A::k()
   {
      cout << n << endl;
   }
  1. Determine what the following program prints, using the nonsense class. Work through this problem by hand, don’t type it in and run it on the computer.
       int main()
       {
          A x,z;
          A y(2);
          A d = A(3);
          z = y;
          x.f();
          y.g();
          z.f();
          d.g();
          d.k();
          A e(x.h() + y.h() + z.h());
          e.k();
          return 0;
       }
    
  2. State which constructor is called during the declaration of each A object in the program shown in the previous problem.
  3. Add a member function int e(A) that returns true if the parameter contains the same value for n as the invoking object, and returns false otherwise.
  4. Write the definition for a class B which has two data members: val (a float) and myA (an A object), and member functions:
    1. default constructor (sets val to 1)
    2. void p(), which multiplies val by 10 and increments data member n of the data member myA in the invoking object
    3. void q(float), which divides val by its parameter
    4. void pr(), which prints the data members of the invoking object
  5. Write a main function which declares two B objects called bOne and bTwo, and an A object called aOne. This function should
    1. set the data member of aOne to 9
    2. set the myA data member of bOne to contain 3, and the val data member of bOne to 10
    3. print all three objects

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2006