Suppose we have to design a video game that manipulates objects of many different types, including objects of classes Martian
, Venutian
, Plutonian
, SpaceShip
and LaserBeam
. Imagine that each of these classes inherits from the common base class SpaceObject
, which contains the member function draw
. Each derived class implements this function in a manner appropriate for that class. A screen-manager program maintains a container (e.g., a vector
) that holds SpaceObject
pointers to objects of the various classes. To refresh the screen, the screen manager periodically sends each object the same message—namely, draw
. Each type of object responds in a unique way. For example, a Martian
object might draw itself in red with the appropriate number of antennae, a SpaceShip
object might draw itself as a silver flying saucer, and a LaserBeam
object might draw itself as a bright red beam across the screen. The same message (in this case, draw
) sent to a variety of objects has many forms of results—hence the term polymorphism.
A polymorphic screen manager facilitates adding new classes to a system with minimal modifications to its code. Suppose that we want to add objects of class Mercurian
to our video game. To do so, we must build a class Mercurian
that inherits from SpaceObject
, and provides its own definition of member function draw
. Then, when pointers to objects of class Mercurian
appear in the container, you do not need to modify the code for the screen manager. The screen manager simply invokes member function draw
in the same way on every object in the container, regardless of the object’s type, so the new Mercurian
objects just “plug right in.” Thus, without modifying the system (other than to include— and create objects of—the new classes), you can use polymorphism to accommodate additional classes, including ones that were not even envisioned when the system was created.
Polymorphism enables you to deal in generalities and let the execution-time environment concern itself with the specifics. You can direct a variety of objects to behave in manners appropriate to those objects without even knowing their types—as long as those objects belong to the same inheritance hierarchy and are being accessed off a common base-class pointer or a common base-class reference.
Polymorphism promotes extensibility: Software written to invoke polymorphic behavior is written independently of the specific types of the objects to which messages are sent. Thus, new types of objects that can respond to existing messages can be incorporated into such a system without modifying the base system. Only client code that instantiates new objects must be modified to accommodate new types.