CSE2050 Final Exam, 4/30/03, Open books, open notes. Name _________________ 1. What do each of the following print? (4 points each) ANSWER (Notes) int a[4]={10,20,30,40}; cout << a[1/2]; 10 a[0] int* p=a+1; cout << a-p; -1 pointer subtraction cout << p[1]; 30 p[1] is *(p+1) is *(a+2) is a[2] const int& r = *p; cout << r+1; 21 r is p[0] is a[1] cout << --*++p; 29 changes a[2] from 30 to 29 2. Circle True or False (2 points each) The following will sort a above: sort(a.begin(), a.end()); F sort(a, a+4); a[4] == 40 F out of bounds p is a random iterator. T A derived object may be passed to a function expecting a base class. T Passing by value is faster than passing by reference. F slower Temporary objects may only be passed by reference. F Static objects should never be returned by reference. F A class with protected constructors is abstract. T A class with a virtual destructor is abstract. F An input iterator may be passed to a function expecting a forward F iterator. A derived class constructor should initialize inherited data members. F should initialize base class instead back_inserter() returns an output iterator. T The following statement is valid: throw 1; T When an exception is caught, the program terminates. F Only member functions can be friends. F Member functions which do not modify data members should be const. T Member function f is const in this declaration: const int f(); F int f() const; Templated code may appear in a header file. T A derived pointer may point to a base object. F other way around Given classes Person and Student, the base class would be Person. T 3. A School associates names with a list of grades. When a School is printed, each name appear on a separate line (ordered alphabetically) followed by the grades in the order that they were assigned, e.g. School fit; fit.assign("John", 93); fit.assign("Alice", 82); fit.assign("John", 71); cout << fit; // Prints: Alice 82 // John 93 71 School is implemented as follows. Overload << to print Schools. (20 points) struct School: public map > { void assign(const string& name, int grade) { (*this)[name].push_back(grade); } }; // ANSWER ostream& operator << (ostream& out, const School& s) { for (School::const_iterator p=s.begin(); p!=s.end(); ++p) { out << p->first; // out, not cout for (int i=0; isecond.size()); ++i) out << " " << p->second[i]; out << endl; } return out; // Don't forget } // NOTES: // p could also be map >::const_iterator // The inner loop could also use iterators (vector::const_iterator) // Must use const_iterator (not iterator) because s is const. // You cannot sort a map. School is already sorted by name. 4. Write the member functions required by the rule of 3. (20 points) template class X { Y* p; public: X(int i): p(new Y(i)) {} // ANSWER - should copy/assign object pointed to by p ~X() {delete p;} // Not delete[] p; X(const X& x): p(new Y(*x.p) {} X& operator=(const X& x) { *p = *x.p; return *this; } };