Procedure Overloading

Overloading means that several procedures, each with different arguments of different types, can be referred to using a single name. The compiler then decides which procedure should be called on the basis of the number and/or type of arguments supplied. Procedure overloading is useful because it promotes readability and brevity in the calling program. As an example, consider overloading the assignment operator (=) so that we can use this operator between two user-defined types (vectorType in this case):

 integer :: n=3
 real :: a(3)
 real :: magnitude
 module procedure equalVectorType
left%a(i) = right%a(i)
type(vectorType),intent(in) :: right
type(vectorType),intent(inout) :: left
integer :: i
left%n = right%n
left%magnitude = right%magnitude
do i = 1,right%n
enddo

module vector
implicit none
private
type,public :: vectorType
end type vectorType

! Allow assignment operator to be used between
! vector types
interface assignment(=)
end interface
contains
subroutine equalVectorType (left,right)
end subroutine equalVectorType
end module vector

This module can be used in the main program as follows:

program overloadTest

! make the data and functions in vector module
! available to this program
use vector
implicit none

! Create two new vectors
type(vectorType) :: v1, v2
integer :: i

! Set some test values
v1%a(1) = 1.0; v1%a(2) = 1.0; v1%a(3) = 0.0
v2%a(1) = 0.0; v2%a(2) = 0.0; v2%a(3) = 0.0

! Set v2 equal to v1
v2 = v1
write (*,*) (v2%a(i), i = 1,v2%n)
end program overloadTest
Program Output:
 1.00000000      1.00000000       0.0000000

Supported By

File Browser Reference
Department FHERIS
University of Galway
HEA Logo