In C++, polymorphism lets a variable refer to objects of differentdata types. The only catch is that the different data types must bemembers of the same inheritance hierarchy and they must be lower in thehierarchy than the variable's data type. The cool part is this abilitylets the same instruction behave differently, based on the actualobject's data type instead of the variable's data type.
Consider the hierarchy of the UML class diagram in Figure 1. Here, Ihave derived the Manager and Salesperson classes fromthe Employee class. This lets me use an Employee pointer to point to an Employee , Manager , or Salesperson object.
|Figure1: A class hierarchy|
The following code is an attempt at polymorphism:
Employee* pEmp = new Manager;
cout << *pEmp << endl;
However, this attempt fails since the code does not invoke the Manager 'sinsertion operator (<<) as I intended—it invokes the Employee 'sinsertion operator. This happens because the indirection operation (*)is performed first, so *pEmp returns the data type of thepointer.
In this case, because pEmp is an Employee pointer,the *pEmp operation returns the Employee data type inspite of pointing to a Manager object. After *pEmp isdone, the function call is matched using the Employee datatype. Consequently, the Employee 's insertion function ismatched and not the Manager 's function as intended.
In C++, polymorphism normally requires virtual methods. Because onlymethods can be inherited, many programmers think the insertion(<<) and extraction (>>) operators cannot displaypolymorphic behavior because these operators are implemented asnonmember friend functions.
However, there are several ways of making these operatorspolymorphic. In this article, I compare and contrast three differenttechniques.
Michael Dowell is an AssistantProfessor of Computer Science at Augusta State University. He can becontacted at firstname.lastname@example.org.