TExcelTAD
Home › Fortran › Fortran Type-Bound Procedures

Fortran Type-Bound Procedures

Fortran 2003 added object-oriented programming. Its first building block is the type-bound procedure: a procedure attached to a derived type and called with the % syntax, like a method in other languages. Together with private components, it lets a type control how its data is used.

Methods with contains inside a type

A type definition can have its own contains section listing procedures bound to it. The procedure's first argument, the passed-object dummy (conventionally named self or this), receives the object the method was called on. It must be declared with class(type_name) rather than type(type_name); the next lesson explains why.

fortran · try it yourself
module account_mod
  implicit none
  private
  public :: account

  type :: account
    character(len=20) :: owner = ''
    integer :: cents = 0
  contains
    procedure :: deposit
    procedure :: withdraw
    procedure :: report
  end type account

contains

  subroutine deposit(self, amount)
    class(account), intent(inout) :: self
    integer, intent(in) :: amount
    self%cents = self%cents + amount
  end subroutine deposit

  subroutine withdraw(self, amount, ok)
    class(account), intent(inout) :: self
    integer, intent(in) :: amount
    logical, intent(out) :: ok
    ok = amount <= self%cents
    if (ok) self%cents = self%cents - amount
  end subroutine withdraw

  subroutine report(self)
    class(account), intent(in) :: self
    print '(a, a, i0, a, i2.2)', trim(self%owner), ': 
  

, self%cents / 100, '.', mod(self%cents, 100)
  end subroutine report

end module account_mod

program bank
  use account_mod
  implicit none
  type(account) :: acc
  logical :: ok

  acc = account(owner='Noor')
  call acc%deposit(15000)
  call acc%withdraw(4250, ok)
  print '(a, l1)', 'first withdrawal ok: ', ok
  call acc%withdraw(20000, ok)
  print '(a, l1)', 'second withdrawal ok: ', ok
  call acc%report()
end program bank
first withdrawal ok: T
second withdrawal ok: F
Noor: $107.50

call acc%deposit(15000) is equivalent to calling deposit(acc, 15000): the object is passed automatically as the first argument.

Function methods

Type-bound functions are used in expressions:

fortran · try it yourself
module rect_mod
  implicit none
  private
  public :: rectangle

  type :: rectangle
    real :: width, height
  contains
    procedure :: area
    procedure :: perimeter
    procedure :: is_square
    procedure :: scaled
  end type rectangle

contains

  pure real function area(self)
    class(rectangle), intent(in) :: self
    area = self%width * self%height
  end function area

  pure real function perimeter(self)
    class(rectangle), intent(in) :: self
    perimeter = 2.0 * (self%width + self%height)
  end function perimeter

  pure logical function is_square(self)
    class(rectangle), intent(in) :: self
    is_square = abs(self%width - self%height) < 1.0e-6
  end function is_square

  pure function scaled(self, factor) result(r)
    class(rectangle), intent(in) :: self
    real, intent(in) :: factor
    type(rectangle) :: r
    r = rectangle(self%width * factor, self%height * factor)
  end function scaled

end module rect_mod

program shapes
  use rect_mod
  implicit none
  type(rectangle) :: r, big

  r = rectangle(3.0, 4.0)
  print '(a, f6.2)', 'area:      ', r%area()
  print '(a, f6.2)', 'perimeter: ', r%perimeter()
  print '(a, l1)',   'square?    ', r%is_square()
  big = r%scaled(2.5)
  print '(a, 2f6.2, a, f6.2)', 'scaled:   ', big%width, big%height, ' area ', big%area()
end program shapes
area:       12.00
perimeter:  14.00
square?    F
scaled:     7.50 10.00 area  75.00

Encapsulation: private components

Making components private forces users to go through the methods, so the type can guarantee its invariants. Since a private-component type can't be built with the default constructor outside its module, we provide a constructor function under the type's name with a generic interface:

fortran · try it yourself
module temperature_mod
  implicit none
  private
  public :: thermometer

  type :: thermometer
    private
    real :: kelvin = 273.15
  contains
    procedure :: set_celsius
    procedure :: celsius
    procedure :: fahrenheit
  end type thermometer

  interface thermometer               ! custom constructor
    module procedure new_thermometer
  end interface

contains

  function new_thermometer(celsius) result(t)
    real, intent(in) :: celsius
    type(thermometer) :: t
    call t%set_celsius(celsius)
  end function new_thermometer

  subroutine set_celsius(self, c)
    class(thermometer), intent(inout) :: self
    real, intent(in) :: c
    self%kelvin = max(0.0, c + 273.15)   ! never below absolute zero
  end subroutine set_celsius

  real function celsius(self)
    class(thermometer), intent(in) :: self
    celsius = self%kelvin - 273.15
  end function celsius

  real function fahrenheit(self)
    class(thermometer), intent(in) :: self
    fahrenheit = self%celsius() * 9.0 / 5.0 + 32.0
  end function fahrenheit

end module temperature_mod

program use_thermometer
  use temperature_mod
  implicit none
  type(thermometer) :: t

  t = thermometer(21.5)
  print '(a, f8.2, a, f8.2)', 'C: ', t%celsius(), '   F: ', t%fahrenheit()
  call t%set_celsius(-500.0)            ! clamped
  print '(a, f8.2, a, f8.2)', 'C: ', t%celsius(), '   F: ', t%fahrenheit()
end program use_thermometer
C:    21.50   F:    70.70
C:  -273.15   F:  -459.67

Outside the module, t%kelvin is not accessible: the only way to change the temperature is set_celsius, which enforces the lower limit.

Generic type-bound procedures and nopass

A type can bind a generic name to several specific methods, and a method can opt out of receiving the object with nopass:

fortran
type :: logger
contains
  procedure :: log_int, log_real
  generic :: log => log_int, log_real     ! call obj%log(42) or obj%log(3.5)
  procedure, nopass :: version            ! called as obj%version(), no self argument
end type logger

Types can also bind operators the same way: generic :: operator(+) => add.

Finalizers

A final procedure runs automatically when an object is destroyed (goes out of scope or is deallocated). It's useful for releasing resources such as file units or pointer-based memory:

fortran
type :: resource
  integer :: unit = -1
contains
  final :: close_resource
end type resource

Test yourself

What is the passed-object dummy argument?

  1. A global variable
  2. The first argument of a type-bound procedure, which receives the object it was called on
  3. An optional argument
  4. The return value

How must the passed-object dummy be declared?

  1. type(t), intent(in) :: self
  2. class(t), intent(...) :: self
  3. pointer :: self
  4. self needs no declaration

Why provide a constructor function for a type with private components?

  1. Private components can't be set by the default structure constructor outside the module
  2. Constructors run faster
  3. Fortran requires a constructor for every type
  4. To make the type abstract