Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Derived Types and Pointers

Type-Bound Procedures and Object-Oriented Fortran

Attach procedures to derived types with the contains section, call them with the object%method syntax, use passed-object dummies, constructors and final procedures.

Since Fortran 2003 a derived type can carry its own procedures. A type-bound procedure is declared in the type and called as object%name(args), just like a method in other object-oriented languages. The type plus its bound procedures is Fortran's class. This lesson shows how to build one, hide its data and clean up after it. Polymorphism and abstract types comes next.

A class in Fortran

FORTRAN
module stack_mod
  implicit none
  private
  public :: int_stack

  type :: int_stack
    private
    integer, allocatable :: items(:)
    integer :: count = 0
  contains
    procedure :: push
    procedure :: pop
    procedure :: size => stack_size
    procedure :: is_empty
  end type int_stack

contains

  subroutine push(self, v)
    class(int_stack), intent(inout) :: self
    integer, intent(in) :: v
    integer, allocatable :: tmp(:)
    if (.not. allocated(self%items)) allocate(self%items(4))
    if (self%count == size(self%items)) then
      allocate(tmp(2 * size(self%items)))
      tmp(1:self%count) = self%items
      call move_alloc(tmp, self%items)
    end if
    self%count = self%count + 1
    self%items(self%count) = v
  end subroutine push

  function pop(self) result(v)
    class(int_stack), intent(inout) :: self
    integer :: v
    v = self%items(self%count)
    self%count = self%count - 1
  end function pop

  integer function stack_size(self)
    class(int_stack), intent(in) :: self
    stack_size = self%count
  end function stack_size

  logical function is_empty(self)
    class(int_stack), intent(in) :: self
    is_empty = (self%count == 0)
  end function is_empty

end module stack_mod

Using it:

FORTRAN
program use_stack
  use stack_mod
  implicit none
  type(int_stack) :: s
  integer :: i

  do i = 1, 6
    call s%push(i * 10)
  end do
  print *, s%size()        ! 6
  print *, s%pop()         ! 60
  print *, s%size()        ! 5
end program use_stack

Key points:

  • The contains section inside the type lists the bound procedures. The procedures themselves are ordinary module procedures.
  • procedure :: push binds a procedure of the same name; procedure :: size => stack_size binds a differently named one under the name size.
  • The first dummy argument is the passed-object dummy (called self here, but any name works). It must be class(int_stack), not type(int_stack), so the procedure can also be used by extended types. The object before the % is passed there automatically.
  • private components stop outside code from touching items and count. Callers go through the methods.
  • move_alloc(from, to) moves an allocation without copying and deallocates from. It is the idiomatic way to grow an array.
Python Stand-in: the same stack as a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Passed-object control

By default the object becomes the first argument. Use nopass for a procedure that does not need it, or pass(name) to choose a different argument:

FORTRAN
type :: calc
contains
  procedure, nopass :: version
  procedure, pass(c) :: scale_by
end type calc

nopass is the Fortran analogue of a static method.

Constructors

Fortran has no special constructor syntax, so there are two conventions. The first is a module function named after the type, made generic with the type name:

FORTRAN
type :: counter
  integer :: n = 0
  character(len=20) :: label = ""
end type counter

interface counter
  module procedure make_counter
end interface counter

! function make_counter(label) result(c) sets c%label = label

With that interface, c = counter("hits") calls your function while the default structure constructor counter(0, "hits") still works. The second convention is an explicit init method that you call on an existing object.

Final procedures (destructors)

Mark a procedure with final to run automatically when an object is deallocated or goes out of scope:

FORTRAN
type :: file_handle
  integer :: unit = -1
contains
  final :: close_handle
end type file_handle

subroutine close_handle(self)
  type(file_handle), intent(inout) :: self
  if (self%unit >= 0) close(self%unit)
end subroutine close_handle

Finalization support has varied between compilers, so for critical cleanup also provide an explicit close method and call it yourself.

Generic bindings

Bind several procedures under one generic name, including operators and assignment:

FORTRAN
type :: vec2
  real :: x = 0.0, y = 0.0
contains
  procedure :: add_vec
  procedure :: add_scalar
  generic :: operator(+) => add_vec
  generic :: add => add_vec, add_scalar
end type vec2

After this, a + b works for two vec2 values and a%add(...) accepts either argument type. Compare this with the free-standing operator interfaces in interfaces and generic procedures: bound generics keep everything inside the type.

When to use it

Type-bound procedures are not mandatory. A module with plain procedures that take a type(...) argument is perfectly good Fortran, and for numerical kernels it is often simpler and faster. Use classes when you want:

  • encapsulation (hidden data, a small public interface),
  • polymorphism (several types with one interface),
  • objects that manage a resource.

Parts of a Fortran class

type Data components
contains Bound procedures
class(t) The passed object
final Cleanup on destruction
1 / 2

Common mistakes

  • Declaring the passed object as type(...) instead of class(...).
  • Forgetting that the passed object is the first argument when you call the procedure directly.
  • Making every component public, which defeats encapsulation.
  • Relying on final for essential cleanup on a compiler whose support is partial.
  • Calling s%pop() on an empty stack: check is_empty() first, as the stack above does not guard against it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How is a type-bound procedure called?

    The object comes before the percent sign and is passed automatically as the first argument.
  2. 2. Why must the passed-object dummy be declared class(...)?

    class(t) means t or any type that extends it, which is needed for inheritance and polymorphism.
  3. 3. What does procedure, nopass bind?

    nopass skips the passed-object argument, like a static method.
  4. 4. What does move_alloc(tmp, items) do?

    It transfers ownership of the memory, which makes growing arrays cheap.

Summary

  • Put contains and procedure :: inside a type to bind procedures; call with obj%name(...).
  • The first argument is the passed object, declared class(type); nopass and pass(name) adjust this.
  • Hide data with private components; use generic bindings and constructor functions for convenience.
  • final procedures clean up but are not reliable everywhere; add an explicit close.

Next: Polymorphism and abstract types