CHAPTER 15

POLYMORPHISM, TEMPLATE, AND ADT 

Polymorphism consists of two words: poly, which means “many,” and morph, which means “form.” In programming, polymorphism is the ability to have many forms for the same name.  An example of polymorphism is when different functions do a similar task and have the same function name or similarly when using many forms for the same operator. Polymorphism, encapsulation, and inheritance are three important features of object-oriented programming. Function overloading and operator overloading are two examples of polymorphism. A user function or a built-in operator can be overloaded while performing what it was originally designated to do. A computer teacher can become overloaded by teaching an additional math or other course. One form of polymorphism is function overloading. For example, the same function name:  print( ) prints the list of items in a queue or a stack, regardless if they were created statically or dynamically. Another example of polymorphism is operator overloading which adds a new meaning to most of the C++ operators. C++ operators are defined for the basic data types; with operation overloading, the same operators can be applied to user-defined types, keeping the operation in the same form as it is applied to the basic types. The goal of operator overloading is to allow user defined types (classes) to behave in the same way as built-in types.  Polymorphism contributes to the concept of abstraction by providing a meaningful name that can be used differently for several similar functions and operations. Therefore, a programmer can focus on the function’s and operator’s work rather than getting involved in the overwhelming details of the implementation. As long as the same interface is exposed, the implementation is irrelevant. Finally, for a language to be considered an object-programming language, it must support the features of polymorphism. C++ templates allow programmers to code and reuse code regardless of the specific data type. When the type of data is defined, the compiler will generate the code as if it was written for that specific data type. 

FUNCTION OVERLOADING 

A function is overloaded when the same function name is used to perform different tasks depending on the data type. Function overloading is one of the simplest forms of polymorphism. In the following program, there are three versions of findsmaller( ); each version of the function takes and returns a different data type. The function findsmaller( ) is referred to as an overloaded function.  Without the use of function overloading, the same program would require three different function names to perform the same task.