Lab #12, Friday April 13

The purpose of this lab is to give you practice with virtual functions and polymorphism.

Start with a completed Lab 11. At the end of this lab you had modified main.cpp with:

  Shape *s = &ovals[i];
  s->draw();

The program should have drawn a red X, using the draw function defined in the Shape class.

To do:

  1. Make the draw() function virtual in the Shape class. Re-run the program. It should now draw the shapes instead of the red X, because with virtual functions, the function invoked is the one associated with the object when it was created.

  2. Modify main.cpp so that instead of two arrays of size 3 of type Oval and Rectangle, there is a single array of size 6 of pointers to Shape objects. The definition will look like this:

    Shape *shapes[6];

  3. In the init function, modify the code so that the ovals and rectangles are stored in the shapes array. For example:

    shapes[0] = new Oval("Oval 1", 10, 10, 100, 100);

    (This results in a potential memory leak without a delete, but don't worry about that for this lab)

  4. Modify the display() and handleButton() functions so they loop over the shapes array instead of the old arrays for ovals and rectangles. When this step is done the program should run like the final version from Lab 11 except you are now using a single array of Shapes.

  5. Add protected variables of type float named r,g, and b to the Shape class. These variables will store a value between 0-1 to hold a color in RGB format. Add a new public function named changeColor that sets r, g, and b to random values between 0 and 1. You can get a random float between 0 and 1 with the code:

    r = (float)rand() / RAND_MAX;

    Update the Shape constructors so they both call changeColor to initialize the color to a random value. Finally, update the draw() function in Oval and Rectangle to use the r,g,b variables when setting the color.

  6. Modify the handleButton function in main so that when the shape is clicked, that shape's color is changed to a new random color and redrawn. Nothing should happen when the mouse button is released.

Show your working code / answers to the instructor or lab assistant for credit, or email your solution by midnight.