CSE2050 Spring 2005 Exam #2, open book, open notes. Name _________________ 1. Given the following implementation of class Complex, add the destructor, copy constructor and assignment operator (40 pts). template class Complex { T *rp, *ip; // pointers to real and imaginary parts public: T real() const {return *rp;} T imag() const {return *ip;} Complex(T r=0, T i=0): rp(new T(r)), ip(new T(i)) {} // ANSWER ~Complex() { delete rp; // no [] delete ip; } Complex(const Complex& c): rp(new T(c.real())), ip(new T(c.imag())) {} Complex& operator = (const Complex& c) { // or complex& *rp = c.real(); // or *rp = *c.rp; *ip = c.imag(); return *this; } }; 2. Write a templated operator << to output Complex in the form "x+yi", for example (20 pts). Complex a(3, 4); const Complex d=2.5; cout << a << " " << d << endl; // 3+4i 2.50000+0.00000i // ANSWER template ostream& operator << (ostream& out, const Complex& c) { out << c.real() << "+" << c.imag() << "i"; return out; } 3. How many Complex objects are created in each of the following statements? Assume that the arithmetic operators are overloaded with their usual meaning and that their operands are passed by const reference and returned by value (4 pts each). ANSWERS Complex a(1, 2), b=3, c=a, d, e[10], *p; 14 (10 in e, none in p) cout << a+5; 2 (temp 5+0i and 6+2i) a=b; 0 a=b.real(); 1 (temp 3+0i) p=new Complex(5); 1 (5+0i) 4. Circle True or False (4 pts each). ANS. F The "const" in real() means it returns a constant. F The "const" in imag() means it can only be called on a const object. F real() returns by reference. T The Complex constructor parameters are copies of the arguments. T A function should not return a local variable by reference. (The "const" in real()/imag() means that they do not modify the object and therefore they may be called on a const object. real() returns by value.)