1 2 3 4 5 6 7 8 9 10 11 12

Derivation

In C++ we can derive a class from a previously defined one. For example we might need Circle, SquareandTriangle objects which can be derived from some general class called Shape.If every shape has in common a colour and an x-y position, and if every shape can change its position and colour, then we could start with:

class Shape {
public:
void change_colour (int new_colour);
void move (int x_change, int y_change);
......
private:
int x, y;// coordinates of the origin
int colour;// current colour
.....
};

Shapeis said to be the base class, while Circle, Square and Triangleare derived classes. The aim here is to make it possible to re-use code on a grand scale.

base class
Shape

IMAGE imgs/lec-1801.gif

CircleSquareTriangle
derived classes

If we want to add, say, a Pentagonwe need only code the part that is different from Shape.

March 11, 1998

Page 10

C201/TAM