Question 2-1

Name and explain a reason why generics (such as generic packages in Ada or templates in C++) are a useful feature for a programming language to include.

Solution

A generic allows the programmer to write subprograms in which a type can vary. For example, you could write a Sort subprogram that works with an array of any type of data by using a generic. Without generics, in a statically typed language, you would need a separate sort subprogram for each type of array you might want to sort.

(A more minor, but still legitimate, advantage is that generics allow the programmer to write a generic subprogram that takes a constant as a parameter, and this constant could be compiled into by the compiler into individual instances of the generic subprogram. For example, we could have a generic function that multiplies a number by a generic parameter.

generic
    Mult : Integer
function Multiply(X : Integer) return Integer is
begin
    return Mult * X;
end Multiply;

function Double is new Multiply(2);
function Triple is new Multiply(3);
The compiler will be able to optimize the Double routine to do a left-shift instead of a multiplication.)

Object-oriented features

Back to Review for Quiz 2