Spring 2005 Exam #3, open book, open notes. Name _________________________ 1. Given the following classes, what should the base class be? (It might not be among those listed). (5 pts each). ANSWER a. Real, Complex, Integer Complex (Real x is also Complex x + 0i) b. Vehicle, Car, Truck Vehicle c. Bird, Fish, Dog Animal Which of these base classes would likely be abstract? (5 pts). ANSWER: Animal (because it was created just to derive from). 2. Add the destructor and two other "rule of 3" members. (30 pts). class Complex: public ComplexBase { static list data; // alternating imag/real data for all Complex list::iterator pr, pi; // points to real/imaginary parts public: Complex(double r=0, double i=0) { data.push_front(r); pr=data.begin(); data.push_front(i); pi=data.begin(); } double real() const {return *pr;} double imag() const {return *pi;} // ANSWER ~Complex() { data.erase(pr); data.erase(pi); } Complex(const Complex& c) { data.push_front(c.real()); pr=data.begin(); data.push_front(c.imag()); pi=data.begin(); } Complex& operator=(const Complex& c) { *pr = c.real(); *pi = c.imag(); return *this; } }; 3. Write ComplexBase as an interface (abstract) (20 pts). // ANSWER class ComplexBase { virtual double real() const = 0; virtual double imag() const = 0; virtual ~ComplexBase() {} }; 4. Circle Y if the following statements are legal (in the order shown) or N if not. Assume correct answers to 2 and 3. (3 pts each). ANSWERS Y Complex c; N ComplexBase b; N Complex *cp = new ComplexBase(1,2); Y ComplexBase *bp = new Complex(3); Y cout << bp->real(); N bp.imag() = 0; Y Complex operator+(const ComplexBase& a, const ComplexBase& b); Y c=c+c; N throw Complex; Y try {} catch (const ComplexBase& be) {}