CSE2050 Fall 2004 Exam #2, open book, open notes. Name ___________________ 1. Circle True or False (3 pts each). ANSWERS T A struct is a class whose members are public by default. T It is good design to make data members private. F new int(10) returns a pointer to an array of 10 ints. (new int[10] does) T new throws bad_alloc if it fails. F Memory allocated with new is deleted when the pointer to it goes out of scope. T An operator can be overloaded as either a member or nonmember function. F A const member function cannot be called on a non-const object. T A const member function should not return a reference to a data member. T A constructor taking 1 parameter defines an implicit conversion. T If you don't write a constructor initialization list, the compiler will add one that initializes all data members with no arguments. 2. Write the constructor code for X using an initialization list (10 pts). template class X { int z; public: X(int a=0); // set z=a }; // ANSWER template X::X(int a): z(a) {} 3. Write class Money and overload + and << as in the example below (30 pts). Money a(3, 98), b = 20; // $3.98, $20.00 cout << a+b << endl; // print $23.98 // ANSWER class Money { int cents; // other representations are possible public: int getCents() const {return cents;} Money(int d, int c=0): cents(d*100+c) {} }; Money operator+(const Money& a, const Money& b) { // could also be a member return Money(0, a.getCents()+b.getCents()); } ostream& operator << (ostream& out, const Money& m) { // must be nonmember return out << '$' << m.getCents()/100 << "." << setw(2) << setfill('0') << m.getCents()%100; } 4. Given class Person below, add the 3 member functions required by the rule of 3 (30 pts). class Person { char *name; // array of namelen chars int namelen; public: Person(const string& n): name(new char[n.size()]), namelen(n.size()) { copy(n.begin(), n.end(), name); } // ANSWER (see ch. 11.3.6) // destructor ~Person {delete[] name;} // copy constructor Person(const Person& p): name(new char[p.namelen]), namelen(p.namelen) { copy(p.name, p.name+p.namelen, name); } // assignment Person& operator = (const Person& p) { if (&p != this) { // not assignment to self delete[] name; name = new char[p.namelen]; namelen = p.namelen; copy(p.name, p.name+p.namelen, name); } return *this; } };