Fortran Object Oriented Programming Type constructor


Custom constructors can be made for derived types by using an interface to overload the type name. This way, keyword arguments that don't correspond to components can be used when constructing an object of that type.

module ball_mod
  implicit none

  ! only export the derived type, and not any of the
  ! constructors themselves
  public :: ball

  type :: ball_t
     real :: mass
  end type ball_t

  ! Writing an interface overloading 'ball_t' allows us to
  ! overload the type constructor
  interface ball_t
     procedure :: new_ball
  end interface ball_t


  type(ball_t) function new_ball(heavy)
    logical, intent(in) :: heavy

    if (heavy) then
       new_ball%mass = 100
       new_ball%mass = 1
    end if
  end function new_ball
end module ball_mod

program test
  use ball_mod
  implicit none

  type(ball_t) :: football
  type(ball_t) :: boulder
  ! sets football%mass to 4.5
  football = ball_t(4.5)
  ! calls 'ball_mod::new_ball'
  boulder = ball_t(heavy=.true.)
end program test

This can be used to make a neater API than using separate initialisation routines:

subroutine make_heavy_ball(ball)
  type(ball_t), intent(inout) :: ball
  ball%mass = 100
end subroutine make_heavy_ball


call make_heavy_ball(boulder)