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), ':