Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

The “Shape” example

This is an example of a class hierarchy that uses polymorphism. The generic type is the base class Shape, and the specific derived types are Circle, Square, and Triangle:

This is a typical class-hierarchy diagram, with the base class at the top and the derived classes growing downward. The normal goal in object-oriented programming is for the bulk of your code to manipulate pointers to the base type ( Shape, in this case) so if you decide to extend the program by adding a new class ( rhomboid, derived from Shape, for example), the bulk of the code is not affected. In this example, the virtual function in the Shape interface is draw( ), so the intent is for the client programmer to call draw( ) through a generic Shape pointer. draw( ) is redefined in all the derived classes, and because it is a virtual function, the proper behavior will occur even though it is called through a generic Shape pointer.

Thus, you generally create a specific object ( Circle, Square, or Triangle), take its address and cast it to a Shape* (forgetting the specific type of the object), and use that anonymous pointer in the rest of the program. Historically, diagrams are drawn as seen above, so the act of casting from a more derived type to a base type is called upcasting.

Contents | Prev | Next


Contact: webmaster@codeguru.com
CodeGuru - the website for developers.
[an error occurred while processing this directive]