Skip to content
Derived Types
step 1/5

Reading — step 1 of 5

Learn

~1 min readDerived Types and Allocation

Derived types are Fortran's structs.

type :: point
    real :: x, y
end type

type(point) :: p
p%x = 3.0
p%y = 4.0
print *, p%x, p%y

Note % is the field access — Fortran's equivalent of . in C.

Constructor:

p = point(3.0, 4.0)            ! positional
p = point(y=4.0, x=3.0)        ! named

Type-bound procedures (Fortran 2003+):

type :: point
    real :: x, y
contains
    procedure :: distance_from_origin
end type

contains
    function distance_from_origin(self) result(d)
        class(point), intent(in) :: self
        real :: d
        d = sqrt(self%x**2 + self%y**2)
    end function

The class(point) instead of type(point) enables polymorphism (an extending type can be passed). The self parameter is implicit when called as p%distance_from_origin().

Inheritance with extends:

type, extends(point) :: point3d
    real :: z
end type

point3d automatically has x, y, z. Method dispatch is dynamic when the function takes class(point).

Allocatable components for variable-size data:

type :: vector
    real, allocatable :: data(:)
end type

type(vector) :: v
allocate(v%data(100))

When the vector is destroyed (going out of scope or explicit deallocate), the data is freed automatically.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…