Now suppose you plan to make a picture by grouping a number of these elements together, and you want to draw the picture in a convenient way. One approach is to create an array that holds pointers to all the different objects in the picture. The array might be defined like this: shape* ptrarr[100]; // array of 100 pointers to shapes
If you insert pointers to all the shapes into this array, you can then draw an entire picture using a simple loop:
for(int j=0; j
This is an amazing capability: Completely different functions are executed by the same function call. If the pointer in ptrarr points to a ball, the function that draws a ball is called; if it points to a triangle, the triangle-drawing function is called. This is called polymorphism, which means different forms. The functions have the same appearance, the draw() expression, but different actual functions are called, depending on the contents of ptrarr[j]. Polymorphism is one of the key features of object-oriented programming, after classes and inheritance. For the polymorphic approach to work, several conditions must be met. First, all the different classes of shapes, such as balls and triangles, must be descended from a single base class (called shape in MULTSHAP). Second, the draw() function must be declared to be virtual in the base class.
No comments:
Post a Comment