CSE2050 Final Exam 12/11/02, Open Book, open notes. Name _________________ 1. Circle True or False (2 points each). a. An object declared in a function is destroyed when the function T returns unless the object is declared static. b. The declaration char* p, q; declares both p and q to be pointers. F (q is a char) c. The statement p=new char(100); allocates 100 bytes of memory. F (it allocates 1 byte with initial value 100 or 'd') d. In order for a function to accept expressions (rather than just F variables) as arguments, the parameters must be passed by reference. e. Two overloaded functions with the same name must return the F same type. f. Overloaded operators have higher precedence than built in operators. F g. If a constructor for a derived class does not have an initialization F list, then the base class will not be initialized. h. When an exception is caught, control returns to the place where it F was thrown. i. If every X is a Y, then class X should inherit from class Y. T j. An abstract base class should have a virtual destructor even if T it has no data members. 2. An Array is like a vector or array of T, except that elements are created as needed (with value 0 if T is numeric) so you cannot index out of bounds. It has a const member function list(f) which prints a list of all elements ever accessed and their values to the optional open ofstream f. If the argument is omitted, it prints to cout. Write Array using a map as a base class. (40 points). Array a; // Elements have type int a[5] = 3; // OK a[-2] = 7; // OK cout << a[8]; // OK, 0 a.list(); // Prints [-2]=7 [5]=3 [8]=0 ofstream f("test.txt"); a.list(f); // Prints the same to file test.txt // ANSWER template class Array: public map { public: void list(ostream& f=cout) const { for (const_iterator p=begin(); p!=end(); ++p) f << "[" << p->first << "]=" << p->second << " "; } }; 3. Overload << so that it prints an Array for any T, e.g. (20 points). Array b; b[4]="hi"; b[2]=b[6]; cout << b << endl; // [2]= [4]=hi [6]= // ANSWER template ostream& operator << (ostream& out, const Array& a) { a.list(out); return out; } 4. Given a and b above, indicate which statements are errors, and if not, what they print (4 points each). map* p = new Array(a); // OK, no output cout << p->size(); // 3 (*p is a copy of a) p->list(); // Error, no map::list() p = a; // Error, type mismatch a = b; // Error, type mismatch