December 1998
OP216: OBJECT ORIENTED PROGRAMMING

QUESTION 5

Total Marks: 20 Marks

Click here to access other questions

SUGGESTED SOLUTIONS
Solutions and allocated marks are indicated in green.
Return to Question 5

 

In this question, you are to write a program to update a computer display.
(a) Explain, stating one advantage, the term inheritance in object-oriented programming. [3]
Inheritance is the mechanism of creating a new class (1 mark) that contains all the same data members and member functions as the original class (1 mark). Benefit: allows for code reuse (1 mark).

 

(b) A geometric point consists of an x- and y-coordinate. Define a class Point that contains: (1) two private integers to record the coordinates; (2) a constructor that takes two integers and assigns the first to the x-coordinate and the second to the  y-coordinate; and (3) accessor functions for the two coordinates. [5]
class Point { {
private:
   int x, y; [1]
public:
   Point(int m, int n) { [1]
      x = m; y =n; [1]
   }
   int get_x() {return x; } [1]
   int get_y() {return t; } [1]
};

 

(c) A pixel is a point that has an associated colour, represented as an integer. Use inheritance to define a class Pixel that includes: (1) an accessor method for the colour; (2) a mthod set_colour that takes a colour c, and sets the pixel's colour to c. [4]
class Pixel : public Point { [1]
private:
   int colour; [1]
public:
   void set_colour (int c) { [1]
     colour = c; [1]
   }
};

 

(d) A computer screen is a 480 x 768 matrix of Pixels, defined by the class below.

class Screen {
private:
   const int vertical = 480;
   const int horizontal = 768;
   Pixel screen[vertical][horizontal];
};

 

(i) A pixel is on if its colour is not 0. Write a function pixel_on that takes a point, and returns 1 if the pixel at that point is set or 0 otherwise. [3]
int pixel_on(Point p) { [1]
    return (screen[p.get_x()][p.get_y()]
.get_colour() != 0);
};
[2]
(1 mark) for a correct signature; (1 mark) for accessing correct pixel; (1 mark) for returning correct solution.

 

(ii) Suppose we have two points p1 = (x1, y1) and p2 = (x2,y2), where x1 < x2 and y1 < y2, that form the lower-left and upper-right corners of a rectangle on the screen.
Write a method
fill that takes two point p1 and p2 and a colour c, and sets the colour of every pixel in the rectangle described by p1 and p2 to c. State any assumptions you make.
[5]
void fill(Point p1, Point p2, int c) {
  for (int i=p1.get_x(); i<p2.get_x(); i++) [2]
    for (int j=p1.get_y(); j<p2.get_y(); j++) [2]
      screen[i][j].set_colour(c); [1]
};

(1 mark) each for starting loop at correct location and (1 mark) for each correct guard; (1 mark) for correctly accessing screen[i][j] and setting colour properly.