CSE2050 Exam #3, 4/17/03. Open books, open notes. Name _________________ 1. Consider the following code. What do each of the statements below print? (4 points each) class B { public: B() {cout << "B() ";} ~B() {cout << "~B() ";} virtual void f() const {cout << "B::f() ";} }; class D: public B { public: D() {cout << "D() ";} ~D() {cout << "~D() ";} void f() const {cout << "D::f() ";} }; B g(const B& x) {return x;} void h(B x) {x.f();} ANSWERS ANSWERS ------- ------- a. B b; B() i. g(b); ~B() b. D d; B() D() j. g(d); ~B() c. b.f(); B::f() k. h(b); B::f() ~B() d. d.f(); D::f() l. h(d); B::f() ~B() e. B* p = new D; B() D() m. b=d; b.f(); B::f() f. p->f(); D::f() n. B(); B() ~B() g. delete p; ~B() o. D(); B() D() ~D() ~B() h. B& r=d; r.f(); D::f() NOTES: Whenever a D object is created, the base must also be created, so the sequence is B() D(). When a D is destroyed, so is its base (in reverse order), so the sequence is ~D() ~B(). In question g, the destructor is not virtual (but should be), so the result is ~B(). If it was virtual, it would be ~D() ~B(). In function g() (questions i and j), a temporary copy of x is returned. The temporary is always type B. The temporary is initialized by copying x using the copy constructor for B, which does not print anything. However the temporary must be eventually destroyed, so it prints ~B(). In function h() (questions k and l), x (always type B) is passed by value, so it is created by copying b or the base part of d. The copy constructor for B does not print anything. However, when the function returns, x is destroyed, so ~B() is called. In question m, b still has type B after the assignment (which assigns the base part of d). B() and D() create temporary objects of type B and D respectively. These temporaries are then destroyed. I gave partial credit for partially right answers. 2. Circle true or false (4 points each). a. B is an abstract base class. F (B objects are allowed) b. f() is a pure virtual function. F (there is no =0; ) c. D inherits B's copy constructor. F (constructors don't inherit) d. The constructor for B should be virtual. F (would make no sense) e. The destructor for B should be virtual. T (so delete p would call ~D()) 3. Class Integer represents integers with unlimited range exactly. Class Rational represents fractions of two Integers exactly. All of the usual arithmetic operations are defined (+, -, *, /, ==, <, etc.) Mixed type expressions are allowed, with promotion from int to Integer and Integer to Rational as needed to represent the range of the result. For example, 3*Integer(10)-4 is exactly Integer(26), and (2/Rational(6))*Integer(3) is exactly Rational(1). One class is derived from the other. The base class and all arithmetic operators have already been written. Write the derived class, including code for all remaining member functions. (20 points). // ANSWER // All integers are rational numbers class Integer: public Rational { public: Integer(int i): Rational(i) {} };