Polymorphism

The ability to call member functions for an object without specifying the object's exact type is known as “polymorphism.” The word “polymorphism” means “the ability to assume many forms,” referring to the ability to have a single statement invoke many different functions. In the above example, the pointer person can point to any type of employee, and the name computePay can refer to any of the salary computation functions.

Compare this with the implementation in C provided earlier in this chapter. In C, if all you have is a pointer to an employee, you have to call the compute_pay function shown earlier, which must execute a switch statement to find the exact type. In C++, the statement person->computePay() calls the appropriate function automatically, without requiring you to examine the type of object that person points to. (There is only a tiny amount of overhead, as described in the section “How Virtual Functions are Implemented”.) No switch statement is needed.

Computing salaries is just one example of a task that differs depending on the type of employee. A more realistic Employee class would have several virtual functions, one for each type-dependent operation. An employee-database program would have many functions like computePayroll, all of which manipulate employees using Employee pointers and virtual functions.

In such a program, all the information about any particular type of employee is localized in a single class. You don't have to look at every employee-database function to see how salespersons are handled. All the specialized salesperson processing is contained in the SalesPerson class. It's also easy to add a new type of employee, due to a property known as “dynamic binding.”