CSE2050 Exam #2 11/7/02, Open books, open notes. Name ___________________ 1. Complete the class Complex, below, by adding the three member functions required by the "rule of 3" (40 pts). class Complex { private: double* z; // z[0] is the real part, z[1] is the imaginary part public: double real() const {return z[0];} double imag() const {return z[1];} Complex(double r=0, double i=0): z(new double[2]) { z[0]=r; z[1]=i; } ANSWER ~Complex() {delete [] z;} Complex(const Complex& c): z(new double[2]) { // or z = new double[2]; z[0] = c.real(); // or c.z[0] or *c.z z[1] = c.imag(); // or c.z[1] } Complex& operator = (const Complex& c) { // No need for delete, new, because z is the same size. // Thus, no need to check for assignment to self. z[0] = c.real(); // or c.z[0] or *c.z z[1] = c.imag(); // or c.z[1] return *this; } }; 2. A RealNumber is a Complex whose imaginary part is always 0. Derive RealNumber from Complex, consistent with the example below (30 pts). RealNumber a, b=3; // a defaults to 0 cout << a.real() << ' ' << a.imag() << endl; // 0 0 cout << b.real() << ' ' << b.imag() << endl; // 3 0 Complex c=b; cout << c.real() << ' ' << c.imag() << endl; // 3 0 ANSWER class RealNumber: public Complex { public: RealNumber(double r=0): Complex(r, 0) {} // or : Complex(r) {} // Do NOT initialize z, it is private and initialized by Complex }; // No need to write the destructor, copy consructor, or operator= again // because the default calls these for the base class as required. // Writing them is incorrect because z is private. 3. Write an abstract base class (interface) for Complex called ComplexBase, e.g. (30 pts). ostream& operator << (ostream& out, const ComplexBase& c) { return out << c.real() << "+" << c.imag() << "i"; } int main() { cout << Complex(3,4) << endl; // 3+4i cout << RealNumber(6) << endl; // 6+0i ComplexBase* p = new RealNumber(7); cout << *p << endl; // 7+0i delete p; // Calls the right destructor ComplexBase x; // Error: abstract return 0; } ANSWER (We assume class Complex: public ComplexBase {...}; ) class ComplexBase { public: virtual double real() const = 0; virtual double imag() const = 0; virtual ~ComplexBase() {} // Optional protected constructor, may be omitted protected: ComplexBase() {} };