CSE2050 Exam #3 Fall 2004, open book, open notes. Name __________________ 1. Given class Rectangle, derive class Square with a constructor taking one parameter which is both the width and height (20 pts). class Rectangle: public Shape { private: int width, height; public: Rectangle(int w, int h): width(w), height(h) {} virtual int area() const {return width*height;} }; // ANSWER class Square: public Rectangle { public: Square(int side): Rectangle(side, side) {} }; 2. Write Shape as an ABSTRACT base class (20 pts). // ANSWER class Shape { public: virtual int area() const = 0; virtual ~Shape() {} }; 3. Which of the following statements are legal (assuming all previous statements are legal)? Circle OK or ERROR (3 pts each) ANSWERS Comments -------- -------- ERROR Shape sh; Abstract ERROR Rectangle rec; Constructor requires arguments OK rec.area(); OK Square sq(5); ERROR Square *sp = &rec; No derived pointer to base class OK Rectangle *rp = sp; OK: base pointer to derived object OK rec = sq; OK: derived to base conversion ERROR sq = rec; No base to derived conversion OK const Square *csp = sp; OK: const pointer to non-const object OK sp->area(); OK csp->area(); OK: area() is const OK const Shape *shp = new Square(*sp); OK shp->area(); ERROR rec == sq; Operator == not defined OK Rectangle r(sq); OK: derived to base copy OK Rectangle f(Square s) {return s;} OK: derived to base return ERROR f(rec); No base to derived conversion ERROR f(new Square); Type mismatch: new returns a pointer OK int g(const Shape& s) {return s.area();} OK g(rec);