Type-bound procedures
| Bind procedures | |
| Pass the object | |
| Extend types | |
| Deferred bindings |
Bind procedures
A type-bound procedure connects a subroutine or function to a derived type, so the type carries both data and behavior.
List the binding inside a contains block of the type definition, then implement the procedure in the contains part of the module.
The module below gives a counter type a reset method.
module counters
implicit none
type :: counter
integer :: n = 0
contains
procedure :: reset
end type counter
contains
subroutine reset(self)
class(counter), intent(inout) :: self
self%n = 0
end subroutine reset
end module counters
Pass the object
By default the object before the percent sign is passed as the first dummy argument, which is called the passed-object argument.
Declare that argument with class and the type name, and give it a clear intent such as inout for a method that changes state.
The program below calls the method with call syntax and then prints the result.
program demo
implicit none
use counters
type(counter) :: c
c%n = 41
call c%reset()
print *, c%n
end program demo
Extend types
A new type can extend an existing one with the extends keyword, inheriting both components and bindings of the parent.
The child type adds its own components after the declaration line, while the parent parts stay available as before.
This sketch adds a label to the counter without touching the parent definition.
module named_counters
implicit none
use counters
type, extends(counter) :: named_counter
character(len=20) :: label = "total"
end type named_counter
end module named_counters
Deferred bindings
An abstract type can declare a deferred binding that has no implementation yet, forcing each child type to supply one.
The binding refers to an interface in an abstract interface block, and the import statement makes the type name visible there.
This pattern defines a shape family where every concrete shape must provide its own area function.
module shapes
implicit none
type, abstract :: shape
contains
procedure(area_iface), deferred :: area
end type shape
abstract interface
function area_iface(self) result(a)
import :: shape
class(shape), intent(in) :: self
real :: a
end function area_iface
end interface
end module shapes
Next: Object orientation
Article author: Arthur Isaev