Limitations of Polymorphism in C++

The event-handling scheme described above sounds like a situation that calls for polymorphism. It seems like it should be possible to replace the switch statement with virtual functions. For example, you could give each subclass of Event a virtual respond function. A different action would be taken for each type of event, and you could then write the following:

// Hypothetical example with polymorphic Events

void Win::handleEvent( Event &action )

{

action.respond();

}

However, this would mean that the actions taken for each event would be the same for every type of interactor. A scroll bar would behave in the same way as a text window. This is clearly unsatisfactory.

What is needed is a way to vary the behavior of handleEvent on two parameters: the type of interactor and the type of event. In C it would look like this:

handleEvent( myInteractor, currAction );

Such a function in C would contain a giant switch statement based on the type of interactor, with each case clause containing another switch statement based on the type of event. Through polymorphism in C++, the interactor parameter can be removed by giving the interactor class a virtual handleEvent function, as follows:

myInteractor->handleEvent( currAction );

Unfortunately, C++ does not allow an additional level of polymorphism, which would allow you to remove the event parameter. To retain the polymorphism already in place, you must use a switch statement for the event parameter.

This illustrates a situation where language limitations influence the design. Since C++ doesn't support an ideal solution, this example program has to use a technique that's less than optimal. You should remember that, in general, it's not good practice to use a switch statement to examine an object's type. Only when your design calls for multiple levels of polymorphism is the technique permissible. (A technique that avoids the use of switch statements is outlined in the comments to the source code.)

Remember that the classes' public interfaces are not final until the implementation phase. See the files in the sample program directory for the final interfaces and the implementation code for this example.