Ada Programming/Function overloading

From Wikibooks, open books for an open world
Jump to navigation Jump to search

float
File: function_overloading.adb (view, plain text, download page, browse all)
 function Generate_Number (MaxValue : Integer)  return Integer  is
    subtype Random_Type  is Integer  range 0 .. MaxValue;
    package Random_Pack  is  new Ada.Numerics.Discrete_Random (Random_Type);
 
   G : Random_Pack.Generator;
 begin
   Random_Pack.Reset (G);
    return Random_Pack.Random (G);
 end Generate_Number;


 function Generate_Number (MinValue : Integer;
                          MaxValue : Integer)  return Integer
 is
    subtype Random_Type  is Integer  range MinValue .. MaxValue;
    package Random_Pack  is  new Ada.Numerics.Discrete_Random (Random_Type);
 
   G : Random_Pack.Generator;
 begin
   Random_Pack.Reset (G);
    return Random_Pack.Random (G);
 end Generate_Number;
 Number_1 : Integer := Generate_Number (10);
 Number_2 : Integer := Generate_Number (6, 10);

Function overloading in Ada[edit]

Ada supports all six signature options but if you use the arguments' name as option you will always have to name the parameter when calling the function. i.e.:

Number_2 : Integer := Generate_Number (MinValue => 6,
                                       MaxValue => 10);

Note that you cannot overload a generic procedure or generic function within the same package. The following example will fail to compile:

  package myPackage
    generic
      type Value_Type  is (<>);  
   -- The first declaration of a generic subprogram
   -- with the name "Generic_Subprogram"
    procedure Generic_Subprogram (Value :  in  out Value_Type);
   ...
    generic
      type Value_Type  is (<>); 
   -- This subprogram has the same name, but no
   -- input or output parameters. A non-generic
   -- procedure would be overloaded here.
   -- Since this procedure is generic, overloading
   -- is not allowed and this package will not compile.
    procedure Generic_Subprogram;
   ...
    generic
      type Value_Type  is (<>); 
   -- The same situation.
   -- Even though this is a function and not
   -- a procedure, generic overloading of
   -- the name "Generic_Subprogram" is not allowed.
    function Generic_Subprogram (Value : Value_Type)  return Value_Type;
  end myPackage;

See also[edit]

Wikibook[edit]

Ada 95 Reference Manual[edit]

Ada 2005 Reference Manual[edit]