Concepts of Programming Languages

(Sean Pound) #1

422 Chapter 9 Subprograms


the actual parameters in a method call, but two or more methods have param-
eter profiles that can be matched through coercions, which method should be
called? For a language designer to answer this question, he or she must decide
how to rank all of the different coercions, so that the compiler can choose the
method that “best” matches the call. This can be a complicated task. To under-
stand the level of complexity of this process, we suggest the reader refer to the
rules for disambiguation of method calls used in C++ (Stroustrup, 1997).
Because C++, Java, and C# allow mixed-mode expressions, the return type is
irrelevant to disambiguation of overloaded functions (or methods). The context
of the call does not allow the determination of the return type. For example, if a
C++ program has two functions named fun and both take an int parameter but
one returns an int and one returns a float, the program would not compile,
because the compiler could not determine which version of fun should be used.
Users are also allowed to write multiple versions of subprograms with the
same name in Ada, Java, C++, C#, and F#. Once again, in C++, Java, and C# the
most common user-defined overloaded methods are constructors.
Overloaded subprograms that have default parameters can lead to ambigu-
ous subprogram calls. For example, consider the following C++ code:

void fun(float b = 0.0);
void fun();

fun();

The call is ambiguous and will cause a compilation error.

9.9 Generic Subprograms


Software reuse can be an important contributor to software productivity. One
way to increase the reusability of software is to lessen the need to create dif-
ferent subprograms that implement the same algorithm on different types of
data. For example, a programmer should not need to write four different sort
subprograms to sort four arrays that differ only in element type.
A polymorphic subprogram takes parameters of different types on dif-
ferent activations. Overloaded subprograms provide a particular kind of poly-
morphism called ad hoc polymorphism. Overloaded subprograms need not
behave similarly.
Languages that support object-oriented programming usually support sub-
type polymorphism. Subtype polymorphism means that a variable of type T
can access any object of type T or any type derived from T.
A more general kind of polymorphism is provided by the methods of
Python and Ruby. Recall that variables in these languages do not have types,
so formal parameters do not have types. Therefore, a method will work for any
type of actual parameter, as long as the operators used on the formal parameters
in the method are defined.
Free download pdf