COP 4530: Sample quiz solution

 

 

1. Assume you are in a directory with the following files:

part1.c, part1.o, part2, poem1, poem2, quiz6

 

What does the following command do? ls po*

 

Answer:

 

It lists the files: poem1 and poem2.

 

2. Assume you are in a directory with the following files:

part1.c, part1.o, part2, poem1, poem2, quiz6

 

What does the following command do? cat *[1-6] > temp

 

Answer:

 

It concatenates the contents of files: part2, poem1, poem2, and quiz6, and stores it in a file called temp. Any previous contents of temp are deleted.

 

3. Let i, j, and k be integer variables, with i = j = 1, and k = 3. What is the value of l after execution of the following statement?

 

l = (i<<j)&k;

 

Answer:

 

The value of l will be 2.

 

4. Let i, j, and k be integer variables each having value 3. What are their values after execution of the following statement?

 

i *= ++j*k--;

 

Answer:

 

i = 36, j = 4, and k = 2.

 

5. Define a class called MyInt that has a private int data member called data, two public accessor functions get and set, and a public constructor that takes an int argument.

 

 

Answer:

 

class MyInt

{

private:

  data;

 

public:

  MyInt(int);

  int get();

  void set();

};

 

 

6. Implement the constructor for the class in #5, so that it sets the value of data to the value of its argument.

 

Answer:

 

MyInt::MyInt(int value)

{

  data = value;

}

 

 

7. Implement the get accessor function for the class MyInt.

 

Answer:

 

int MyInt::get()

{

   return data;

}

 

 

8. What is the difference in the restrictions each of the following declarations places on the use of X?

 

(i) const int *X;

(ii) int *const X;

 

Answer:

 

(i) is a non-constant pointer to constant data. So the pointer can be made to point to a different memory location. However, the data in the memory location it points to cannot be modified.

 

(ii) is a constant pointer to non-constant data. So the pointer cannot be made to point to a different memory location, though the data it points to may be modified.

 

 

9. Why do classes with dynamic memory allocation typically overload the assignment operator?

 

Answer:

 

Otherwise, if we performed an assignment such as A = B, then the default assignment operator would only copy the pointer. So the corresponding pointers in A and B would point to the same memory location. In order to provide a true copy, we overload assignment so that it creates additional memory for A, and copies data from the corresponding locations in B.

 

 

10. How will you deallocate memory allocated in the following statement:

double *ptr = new double[10];

 

Answer:

 

delete [] ptr;