Skip to content
LumenaryAcademy
Practice 65 min

Derived types and object-oriented Fortran

Your own types with components, operators and type-bound procedures, then inheritance, abstract types and polymorphism as Fortran 2003 defines them.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

From arrays of numbers to things

Early Fortran had only numbers and arrays of numbers. A simulation of a thousand particles kept their positions in one array, their velocities in another and their masses in a third, and every routine took all of them as separate arguments. Code like that still works, but it is hard to read and easy to get wrong.

Derived types, added in Fortran 90, let you group data into meaningful units: a vector with three components, a particle with a position and a mass, a grid with its dimensions and spacing. Fortran 2003 then added the machinery of object-oriented programming: procedures bound to types, inheritance, polymorphism and abstract types. Fortran's version of these ideas is less flexible than that of C++ or Python, by design, but it is enough to build large, well-structured codes, and it is widely used in modern climate and engineering models.

DefinitionsH

Derived types and operators

Definition— Derived type, component, structure constructor

A derived type is a user-defined type declared with type :: name ... end type. Its parts are components, accessed with the % operator, as in a%x. A structure constructor has the type's name and takes the components in order or by keyword, vec3(1.0_dp, 2.0_dp, 2.0_dp) or vec3(z=1.0_dp, x=3.0_dp); components with default values may be omitted.

fortran
! Derived types: a 3D vector with its own operators
module vectors
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none
  private
  public :: vec3, operator(+), operator(-), operator(*), operator(.dot.), norm

  type :: vec3
     real(dp) :: x = 0.0_dp, y = 0.0_dp, z = 0.0_dp     ! default initial values
  end type vec3

  interface operator(+)
     module procedure add
  end interface
  interface operator(-)
     module procedure subtract
  end interface
  interface operator(*)
     module procedure scale_left
  end interface
  interface operator(.dot.)                          ! a new operator, named with dots
     module procedure dot
  end interface

contains

  elemental function add(a, b) result(c)
    type(vec3), intent(in) :: a, b
    type(vec3) :: c
    c = vec3(a%x + b%x, a%y + b%y, a%z + b%z)
  end function add

  elemental function subtract(a, b) result(c)
    type(vec3), intent(in) :: a, b
    type(vec3) :: c
    c = vec3(a%x - b%x, a%y - b%y, a%z - b%z)
  end function subtract

  elemental function scale_left(s, a) result(c)
    real(dp), intent(in) :: s
    type(vec3), intent(in) :: a
    type(vec3) :: c
    c = vec3(s * a%x, s * a%y, s * a%z)
  end function scale_left

  elemental function dot(a, b) result(d)
    type(vec3), intent(in) :: a, b
    real(dp) :: d
    d = a%x * b%x + a%y * b%y + a%z * b%z
  end function dot

  elemental function norm(a) result(n)
    type(vec3), intent(in) :: a
    real(dp) :: n
    n = sqrt(a .dot. a)
  end function norm

end module vectors

program use_vectors
  use vectors
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none
  type(vec3) :: a, b, origin
  type(vec3) :: path(4)

  a = vec3(1.0_dp, 2.0_dp, 2.0_dp)                  ! structure constructor
  b = vec3(z=1.0_dp, x=3.0_dp)                       ! by keyword; y keeps its default 0
  print '(a, 3f6.2)', 'a + b     = ', a + b
  print '(a, 3f6.2)', '2a - b    = ', 2.0_dp * a - b
  print '(a, f6.2)', 'a . b     = ', a .dot. b
  print '(a, f6.2, a, 3f5.1)', '|a|       = ', norm(a), ', origin = ', origin

  ! Arrays of derived types, and component selection across the array
  path = [vec3(0.0_dp, 0.0_dp, 0.0_dp), vec3(3.0_dp, 4.0_dp, 0.0_dp), &
          vec3(3.0_dp, 4.0_dp, 12.0_dp), vec3(0.0_dp, 0.0_dp, 12.0_dp)]
  print '(a, 4f6.1)', 'heights along the path: ', path%z           ! an array of reals
  print '(a, 3f6.1)', 'leg lengths: ', norm(path(2:4) - path(1:3))   ! elemental on arrays
  print '(a, f6.1)', 'total length: ', sum(norm(path(2:4) - path(1:3)))
end program use_vectors

It prints:

text
a + b     =   4.00  2.00  3.00
2a - b    =  -1.00  4.00  3.00
a . b     =   5.00
|a|       =   3.00, origin =   0.0  0.0  0.0
heights along the path:    0.0   0.0  12.0  12.0
leg lengths:    5.0  12.0   5.0
total length:   22.0
  • Default initialisation. real(dp) :: x = 0.0_dp inside a type gives every new vec3 that value, so origin printed as zeros without being assigned, and vec3(z=1.0_dp, x=3.0_dp) left y at 0. (Unlike a local variable, a default value in a type does not imply save.)
  • Operator overloading. An interface operator(+) block tells the compiler that + between two vec3 values means the function add. You can overload any intrinsic operator, and define new ones whose names are letters between dots, such as .dot. or .cross.; 2.0_dp * a - b and a .dot. b then read like the mathematics.
  • Elemental procedures on types. Because add, subtract and norm are elemental, they work on whole arrays of vec3: path(2:4) - path(1:3) computes all three legs of the path at once.
  • Component selection across arrays. path%z is an ordinary real(dp) array containing the z component of every element, which can be printed, summed or passed anywhere an array is expected.

Note

Arrays of structures or structures of arrays? An array of vec3 stores x, y, z, x, y, z, ... in memory. For loops that use all three components of each point, this is ideal. For loops that only touch x, a "structure of arrays" (one type holding three arrays x(:), y(:), z(:)) keeps the data you use contiguous and vectorises better. High-performance codes choose between the two layouts deliberately.

Worked examplesH

Encapsulation with type-bound procedures

A type-bound procedure is a procedure attached to a type, called with the % syntax, stats%add(x). Its first argument, conventionally named self (or this), receives the object; it is declared class(type_name) so that extended types can use the procedure too. Combined with private components, this gives encapsulation: users of the type can only change its state through its procedures.

fortran
! Encapsulation: a running-statistics object with private state and type-bound procedures
module running_stats_mod
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none
  private
  public :: running_stats

  type :: running_stats
     private                                   ! components hidden outside the module
     integer :: n = 0
     real(dp) :: mean_ = 0.0_dp, m2 = 0.0_dp   ! Welford's algorithm: mean and sum of squared deviations
     real(dp), allocatable :: history(:)
   contains
     procedure :: add
     procedure :: count => get_count
     procedure :: mean => get_mean
     procedure :: variance
     procedure :: last
  end type running_stats

contains

  subroutine add(self, x)
    class(running_stats), intent(inout) :: self
    real(dp), intent(in) :: x
    real(dp) :: delta
    self%n = self%n + 1
    delta = x - self%mean_
    self%mean_ = self%mean_ + delta / self%n
    self%m2 = self%m2 + delta * (x - self%mean_)
    if (.not. allocated(self%history)) allocate(self%history(0))
    self%history = [self%history, x]
  end subroutine add

  pure integer function get_count(self)
    class(running_stats), intent(in) :: self
    get_count = self%n
  end function get_count

  pure real(dp) function get_mean(self)
    class(running_stats), intent(in) :: self
    get_mean = self%mean_
  end function get_mean

  pure real(dp) function variance(self)
    class(running_stats), intent(in) :: self
    variance = self%m2 / (self%n - 1)          ! sample variance
  end function variance

  pure real(dp) function last(self)
    class(running_stats), intent(in) :: self
    last = self%history(size(self%history))
  end function last

end module running_stats_mod

program stats_demo
  use running_stats_mod
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none
  type(running_stats) :: rainfall, copy
  real(dp), parameter :: mm(7) = [12.0_dp, 0.0_dp, 3.5_dp, 27.0_dp, 8.0_dp, 0.5_dp, 15.0_dp]
  integer :: k

  do k = 1, size(mm)
     call rainfall%add(mm(k))
  end do
  print '(a, i0, a, f0.3, a, f0.3)', 'days: ', rainfall%count(), ', mean mm: ', rainfall%mean(), &
        ', sd: ', sqrt(rainfall%variance())

  ! Assignment copies everything, including allocatable components (a deep copy)
  copy = rainfall
  call copy%add(40.0_dp)
  print '(a, i0, a, f0.1)', 'copy: ', copy%count(), ' days, last ', copy%last()
  print '(a, i0, a, f0.1)', 'original: ', rainfall%count(), ' days, last ', rainfall%last()
end program stats_demo

It prints:

text
days: 7, mean mm: 9.429, sd: 9.594
copy: 8 days, last 40.0
original: 7 days, last 15.0
  • Private components. The private statement inside the type hides n, mean_, m2 and history from code outside the module; rainfall%n in the main program would not compile. Users call count(), mean() and variance() instead, so the implementation can change without breaking them.
  • Bindings with different names. procedure :: mean => get_mean binds the module procedure get_mean under the public name mean.
  • Welford's algorithm updates the mean and the sum of squared deviations one value at a time. It is numerically much more stable than accumulating ∑x\sum x and ∑x2\sum x^2 and subtracting at the end, which suffers from the cancellation you met in the previous lesson.
  • Deep copies. copy = rainfall copied every component, including the allocatable history array, so adding a value to copy left rainfall unchanged. Types with allocatable components behave as values: no shared state, no dangling pointers. Types with pointer components, by contrast, copy only the pointer, which is one more reason to prefer allocatable.
ComputationC

Inheritance and polymorphism

Definition— Type extension, polymorphism

A type declared type, extends(parent) :: child extends its parent: it has all the parent's components and type-bound procedures, may add more, and may override inherited procedures. A variable declared class(parent) is polymorphic: it may hold a value of the parent type or of any extension, and calls to its type-bound procedures run the version for the value's actual (dynamic) type.

fortran
! Object-oriented Fortran: an abstract type, extensions, deferred bindings and polymorphism
module shapes
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none
  private
  public :: shape, circle, rectangle, square

  real(dp), parameter :: pi = acos(-1.0_dp)

  type, abstract :: shape
     character(len=:), allocatable :: label
  contains
     procedure(area_interface), deferred :: area     ! every concrete shape must provide area
     procedure :: describe                            ! inherited by all shapes
  end type shape

  abstract interface
     pure function area_interface(self) result(a)
       import :: shape, dp
       class(shape), intent(in) :: self
       real(dp) :: a
     end function area_interface
  end interface

  type, extends(shape) :: circle
     real(dp) :: radius
  contains
     procedure :: area => circle_area
  end type circle

  type, extends(shape) :: rectangle
     real(dp) :: width, height
  contains
     procedure :: area => rectangle_area
  end type rectangle

  type, extends(rectangle) :: square                  ! a square is a rectangle...
  contains
     procedure :: describe => describe_square         ! ...that describes itself differently
  end type square

contains

  pure function circle_area(self) result(a)
    class(circle), intent(in) :: self
    real(dp) :: a
    a = pi * self%radius**2
  end function circle_area

  pure function rectangle_area(self) result(a)
    class(rectangle), intent(in) :: self
    real(dp) :: a
    a = self%width * self%height
  end function rectangle_area

  subroutine describe(self)
    class(shape), intent(in) :: self
    print '(a, a, f8.3)', self%label, ': area ', self%area()   ! dispatches on the dynamic type
  end subroutine describe

  subroutine describe_square(self)
    class(square), intent(in) :: self
    print '(a, a, f8.3, a, f4.2)', self%label, ': area ', self%area(), ', side ', self%width
  end subroutine describe_square

end module shapes

program polymorphism
  use shapes
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none

  type :: shape_holder                                ! Fortran arrays hold one type, so wrap
     class(shape), allocatable :: item
  end type shape_holder

  type(shape_holder) :: garden(3)
  integer :: k
  real(dp) :: total

  allocate(garden(1)%item, source=circle(label='pond', radius=1.5_dp))
  allocate(garden(2)%item, source=rectangle(label='vegetable bed', width=2.0_dp, height=4.5_dp))
  allocate(garden(3)%item, source=square(label='herb box', width=0.8_dp, height=0.8_dp))

  total = 0.0_dp
  do k = 1, size(garden)
     call garden(k)%item%describe()
     total = total + garden(k)%item%area()
  end do
  print '(a, f0.3)', 'total area: ', total

  ! select type recovers the specific type when you need its components
  do k = 1, size(garden)
     select type (s => garden(k)%item)
     type is (circle)
        print '(a, a, f4.2)', s%label, ' has radius ', s%radius
     class is (rectangle)                             ! matches rectangles and squares
        print '(a, a, f4.2, a, f4.2)', s%label, ' is ', s%width, ' by ', s%height
     end select
  end do
end program polymorphism

It prints:

text
pond: area    7.069
vegetable bed: area    9.000
herb box: area    0.640, side 0.80
total area: 16.709
pond has radius 1.50
vegetable bed is 2.00 by 4.50
herb box is 0.80 by 0.80
  • Abstract types and deferred bindings. type, abstract :: shape cannot be instantiated. Its binding procedure(area_interface), deferred :: area says that every non-abstract extension must provide area, with the signature given by the abstract interface. Inside the interface, import :: shape, dp brings those names into the interface's scope, which otherwise does not see the module's declarations.
  • Inheritance. circle and rectangle extend shape and implement area; square extends rectangle, inherits its area, and overrides describe. The inherited describe of shape calls self%area(), which dispatches to the right area for each object, the essence of polymorphism.
  • Polymorphic containers. A Fortran array has one declared type, and elements of a class(shape) array would all have to share one dynamic type. The standard idiom is a small holder type with a class(shape), allocatable component, and an array of holders. Each element is created with sourced allocation, allocate(item, source=circle(...)), which allocates the dynamic type of the source and copies its value. (Fortran 2008 also allows the shorter garden(1)%item = circle(...), but GFortran 11 crashed with a segmentation fault on that form when we tested this program, so the portable allocate(..., source=...) is used here.)
  • select type recovers the specific type when you need components that only it has. type is (circle) matches exactly circle; class is (rectangle) matches rectangle and all its extensions, which is why the square was handled there. Inside each branch, s has the matched type. Use select type sparingly: if you find yourself writing it often, the operation probably belongs in a type-bound procedure.

Fortran offers more in the same vein: generic type-bound procedures (generic :: operator(+) => add_vectors), final procedures that run when an object is deallocated (Fortran's destructors, useful for releasing resources from C libraries), the unlimited polymorphic class(*), which can hold a value of any type, and parameterised derived types such as type(matrix(n=3)), whose compiler support is still uneven.

Worked examplesH

A complete value type: exact fractions

The pieces combine into types that feel built in. Here is an exact fraction type with three features you have not seen yet: a custom constructor that keeps every fraction in lowest terms, generic type-bound operators, and user-defined derived-type I/O, which teaches print and write how to display the type.

fortran
! A constructor that enforces an invariant, generic type-bound operators,
! and user-defined formatted output for an exact fraction type
module fractions
  use, intrinsic :: iso_fortran_env, only: int64
  implicit none
  private
  public :: fraction

  type :: fraction
     private
     integer(int64) :: num = 0, den = 1          ! always in lowest terms, den > 0
   contains
     procedure, private :: add, multiply, equals
     generic :: operator(+) => add
     generic :: operator(*) => multiply
     generic :: operator(==) => equals
     procedure, private :: write_formatted
     generic :: write(formatted) => write_formatted
  end type fraction

  interface fraction                               ! a custom constructor with the type's name
     module procedure make_fraction
  end interface fraction

contains

  function make_fraction(num, den) result(f)
    integer, intent(in) :: num, den
    type(fraction) :: f
    if (den == 0) error stop 'fraction: zero denominator'
    f = normalised(int(num, int64), int(den, int64))
  end function make_fraction

  pure function normalised(n, d) result(f)
    integer(int64), intent(in) :: n, d
    type(fraction) :: f
    integer(int64) :: g
    g = gcd(abs(n), abs(d))
    f%num = sign(1_int64, d) * n / g
    f%den = abs(d) / g
  end function normalised

  pure recursive function gcd(a, b) result(g)
    integer(int64), intent(in) :: a, b
    integer(int64) :: g
    if (b == 0) then
       g = a
    else
       g = gcd(b, mod(a, b))
    end if
  end function gcd

  pure function add(a, b) result(c)
    class(fraction), intent(in) :: a, b
    type(fraction) :: c
    c = normalised(a%num * b%den + b%num * a%den, a%den * b%den)
  end function add

  pure function multiply(a, b) result(c)
    class(fraction), intent(in) :: a, b
    type(fraction) :: c
    c = normalised(a%num * b%num, a%den * b%den)
  end function multiply

  pure logical function equals(a, b)
    class(fraction), intent(in) :: a, b
    equals = a%num == b%num .and. a%den == b%den
  end function equals

  ! Called by write and print for the dt edit descriptor or list-directed output
  subroutine write_formatted(self, unit, iotype, v_list, iostat, iomsg)
    class(fraction), intent(in) :: self
    integer, intent(in) :: unit
    character(len=*), intent(in) :: iotype
    integer, intent(in) :: v_list(:)
    integer, intent(out) :: iostat
    character(len=*), intent(inout) :: iomsg
    if (self%den == 1) then
       write (unit, '(i0)', iostat=iostat, iomsg=iomsg) self%num
    else
       write (unit, '(i0, "/", i0)', iostat=iostat, iomsg=iomsg) self%num, self%den
    end if
  end subroutine write_formatted

end module fractions

program exact
  use fractions
  implicit none
  type(fraction) :: total
  integer :: k

  print '(dt, " + ", dt, " = ", dt)', fraction(1, 2), fraction(1, 3), fraction(1, 2) + fraction(1, 3)
  print '(dt, " normalises to ", dt)', fraction(6, -8), fraction(-3, 4)
  print '(a, l1)', '2/4 == 1/2? ', fraction(2, 4) == fraction(1, 2)

  ! 1/1 + 1/2 + ... + 1/10, exactly
  total = fraction(0, 1)
  do k = 1, 10
     total = total + fraction(1, k)
  end do
  print '(a, dt)', 'harmonic number H(10) = ', total
  print '(a, dt)', '(2/3) * (9/4) = ', fraction(2, 3) * fraction(9, 4)
end program exact

It prints:

text
1/2 + 1/3 = 5/6
-3/4 normalises to -3/4
2/4 == 1/2? T
harmonic number H(10) = 7381/2520
(2/3) * (9/4) = 3/2
  • A constructor with the type's name. The generic interface fraction adds make_fraction as another way to call fraction(...). Because the components are private, code outside the module cannot use the default structure constructor at all, so every fraction goes through make_fraction, which rejects a zero denominator and normalises the sign and common factors: fraction(6, -8) became −3/4. This is the Fortran way to guarantee an invariant.
  • Generic type-bound operators. generic :: operator(+) => add attaches the operator to the type itself, so it travels with the type wherever it is used, even into a module that imports only the type name. The specific procedures are private; users see only the operators.
  • Derived-type I/O. generic :: write(formatted) => write_formatted (Fortran 2003) registers a procedure with a fixed interface that the runtime calls whenever a fraction is written with the dt edit descriptor or with list-directed output. The iotype and v_list arguments carry any options given after dt in a format; this simple version does not use them, which is why GFortran's -Wall warned about two unused dummy arguments when compiling it.
  • Exact arithmetic. The tenth harmonic number, 1+12+⋯+1101 + \tfrac12 + \cdots + \tfrac1{10}, came out exactly as 7381/2520. Using 64-bit integers postpones overflow, but numerators and denominators of sums like this grow quickly, so an exact type for serious use would need arbitrary-precision integers.
ExplanationH

How much object orientation?

Fortran programmers argue about this, and the arguments are worth knowing. Object-oriented design shines at the structure of a large code: a solver that accepts any class(time_integrator), a model component that can be swapped for another implementing the same abstract interface, configuration and I/O objects that keep their state private. Large modern codes, from climate-model components to finite-element frameworks, use it this way.

It is a poor fit for the innermost loops. A type-bound call on a polymorphic object is a run-time dispatch, much like a C++ virtual function call, which can prevent inlining and vectorisation if it happens once per grid cell. The usual pattern is to dispatch once, at the level of a whole array or a whole time step, and inside that call work on plain arrays of numbers with tight loops. Experienced Fortran programmers also keep hierarchies shallow, prefer composition (a type containing another) to deep inheritance, and use pure type-bound functions whenever they can.

Finally, test that your compiler supports what you use. Object-oriented Fortran was standardised in 2003, but compilers took many years to implement it, and corner cases such as polymorphic assignment, finalisation and parameterised types still differ between compilers and versions, as the crash noted above shows. Projects that must build with several compilers test on all of them in continuous integration. When a feature misbehaves, the usual remedy is the one this lesson used: find the simpler, older formulation that every compiler handles (here, sourced allocation instead of polymorphic assignment), write a comment explaining why, and report the bug to the compiler's developers with a minimal example. GFortran's bug tracker and the Fortran Discourse forum are where such reports go.

Common misconceptionsH

Misconceptions

Misconception

"type(shape) and class(shape) are the same." type(shape) declares a variable of exactly that type. class(shape) declares a polymorphic one that can hold any extension, and it must be a dummy argument, an allocatable or a pointer, because its size is not known in advance.

Misconception

"Fortran objects are references, as in Java or Python." Variables of derived type hold their values directly, and assignment copies them, including allocatable components. Sharing requires pointer components or explicit target and pointer variables.

Misconception

"A type-bound procedure needs the object as an explicit argument at the call." The object before the % is passed automatically as the first argument (the passed-object dummy); call rainfall%add(x) calls add(rainfall, x). The nopass attribute turns this off for procedures that do not need the object.

Exercises

Exercises

1. Derived types and object-oriented Fortran

Warm-upComputational

Given

type :: point
   real :: x = 1.0, y = 2.0
end type point

and p = point(y=5.0), what are p%x and p%y? Answer as two numbers separated by a space, e.g. 0.0 0.0.

2. Derived types and object-oriented Fortran

CoreComputational

With .plus. defined as componentwise addition of points, and p = point(1.0, 5.0), what are the components of p .plus. point(10.0, 10.0)? Answer as two numbers, e.g. 0.0 0.0.

3. Derived types and object-oriented Fortran

CoreComputational

With ps = [point(1.0, 0.0), point(2.0, 0.0), point(3.0, 0.0)], what does print '(f5.1)', sum(ps%x) print? Give the number.

4. Derived types and object-oriented Fortran

CoreComputational

type, extends(point) :: point3 adds real :: z = 3.0 to the point type above (whose defaults are x = 1.0, y = 2.0). For a newly declared type(point3) :: r, what are r%x, r%y and r%z? Answer as three numbers.

5. Derived types and object-oriented Fortran

StretchComputational
type :: box
   real, allocatable :: v(:)
end type box
type(box) :: b1, b2
b1%v = [1.0, 2.0]
b2 = b1
b2%v(1) = 99.0
print '(f5.1)', b1%v(1)

What is printed? Give the number.

6. Derived types and object-oriented Fortran

CoreHuman

A subroutine should accept a shape or any type that extends it, and call the right area for each. How should its dummy argument be declared?

Choose one

7. Derived types and object-oriented Fortran

CoreHuman

What does procedure(area_interface), deferred :: area in an abstract type require?

Choose one

8. Derived types and object-oriented Fortran

StretchComputational

In the lesson's program, square extends rectangle. Which branch of this select type handles a square?

select type (s => item)
type is (circle)
   ...
class is (rectangle)
   ...
end select
Choose one

Further reading and resources