CSE2050 Spring 2004 Exam #3, open book, open notes. Name _________________ 1. Circle T for true or F for false (3 pts each). ANSWERS ------- A derived class constructor should initialize inherited data members. F Constructors are never virtual. T Destructors are never virtual. F A pointer to derived class may point at a base object. F If a base class needs a copy constructor, then so does the derived. F A derived class may access inherited protected data members. T A class with pure virtual member functions is abstract. T An abstract class defines an interface to a hierarchy of classes. T A reference to base class may refer to a derived object. T Assignment from derived to base, b=d, changes the type of b to derived. F 2. Which of Tree, Plant, Flower, or Leaf should be a base class? (5 pts) ANSWER: Plant (Flower and Tree are derived from Plant, but Leaf is not.) 3. Write B as an interface for D. Show all code (25 pts). class D: public B { string x; public: D(const string& a = "") {x=a;} string get() const {return x;} }; // ANSWER class B { public: virtual string get() const = 0; virtual ~B() {} // optional: protected: B() {} }; 4. Given B and D above (assuming B is correct), circle OK if the statement compiles or ERROR if not. (3 pts each) ANSWERS ------- B b; ERROR D d; OK cout << D("hi").get(); OK B &r = &d; ERROR (no points off if wrong) D d = B(); ERROR 5. A TestMap is like a map except that it has an extra member function, test(k), which returns true if k is a key in the TestMap (without changing it), as in the example below. Derive TestMap from map and show all code (25 pts). TestMap m; m["hi"]=3.5; bool a = m.test("hi"); // true bool b = m.test("bye"); // false if (a && !b) cout << m.size() << endl; // 1 // ANSWER template class TestMap: public map { public: bool test(const K& k) const { return find(k) != end(); } };