TExcelTAD
Home › Fortran › Fortran Inheritance & Polymorphism

Fortran Inheritance & Polymorphism

A derived type can extend another type: it inherits all components and type-bound procedures of its parent and can add new ones or override inherited methods. Combined with polymorphic class variables, this gives Fortran full object-oriented programming.

extends

fortran · try it yourself
module animals
  implicit none

  type :: animal
    character(len=:), allocatable :: name
    integer :: legs = 4
  contains
    procedure :: describe
    procedure :: sound
  end type animal

  type, extends(animal) :: bird
    real :: wingspan_cm = 0.0
  contains
    procedure :: sound => bird_sound      ! override
  end type bird

contains

  subroutine describe(self)
    class(animal), intent(in) :: self
    print '(a, a, i0, a, a)', self%name, ' has ', self%legs, ' legs and says ', self%sound()
  end subroutine describe

  function sound(self) result(s)
    class(animal), intent(in) :: self
    character(len=:), allocatable :: s
    s = '...'
  end function sound

  function bird_sound(self) result(s)
    class(bird), intent(in) :: self
    character(len=:), allocatable :: s
    s = 'tweet'
  end function bird_sound

end module animals

program zoo
  use animals
  implicit none
  type(animal) :: tortoise
  type(bird) :: robin

  tortoise = animal(name='Tortoise')
  robin%name = 'Robin'
  robin%legs = 2
  robin%wingspan_cm = 22.0

  call tortoise%describe()
  call robin%describe()                         ! inherited method, overridden sound
  print '(a, f5.1)', 'wingspan: ', robin%wingspan_cm
  print '(a, a)', 'parent part: ', robin%animal%name   ! the parent component
end program zoo
Tortoise has 4 legs and says ...
Robin has 2 legs and says tweet
wingspan:  22.0
parent part: Robin
  • type, extends(animal) :: bird inherits name, legs, describe and sound.
  • procedure :: sound => bird_sound overrides sound for birds. The overriding procedure must have the same interface, except that its passed-object argument is class(bird).
  • describe was written only once, for animal, yet robin%describe() prints "tweet": inside describe, self%sound() is dispatched on the dynamic type of self.
  • Every extended type has a component named after its parent (robin%animal) that holds the inherited part.

Polymorphic variables: class

A variable declared class(animal) can hold an animal or any type extended from it. Such variables must be dummy arguments, pointers or allocatables, because their size is only known at run time. An array of a polymorphic wrapper type lets you keep a mixed collection:

fortran · try it yourself
module shapes_mod
  implicit none

  type :: shape
    character(len=10) :: label = 'shape'
  contains
    procedure :: area
  end type shape

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

  type, extends(shape) :: square
    real :: side = 1.0
  contains
    procedure :: area => square_area
  end type square

  type :: shape_holder                 ! wrapper to build a mixed array
    class(shape), allocatable :: item
  end type shape_holder

contains

  real function area(self)
    class(shape), intent(in) :: self
    area = 0.0
  end function area

  real function circle_area(self)
    class(circle), intent(in) :: self
    circle_area = 3.14159265 * self%r**2
  end function circle_area

  real function square_area(self)
    class(square), intent(in) :: self
    square_area = self%side**2
  end function square_area

end module shapes_mod

program polymorphism
  use shapes_mod
  implicit none
  type(shape_holder) :: things(3)
  integer :: i
  real :: total

  allocate(things(1)%item, source=circle(label='coin', r=1.2))
  allocate(things(2)%item, source=square(label='tile', side=3.0))
  allocate(things(3)%item, source=circle(label='plate', r=12.0))

  total = 0.0
  do i = 1, size(things)
    print '(a10, f10.3)', things(i)%item%label, things(i)%item%area()
    total = total + things(i)%item%area()
  end do
  print '(a10, f10.3)', 'total     ', total
end program polymorphism
coin           4.524
tile           9.000
plate        452.389
total        465.913

The loop calls area() without knowing which kind of shape it holds; each object runs its own version. This is dynamic dispatch, and it lets you add new shapes without touching the loop.

allocate(x, source=value) allocates the polymorphic component with the dynamic type of value and copies the value into it. (Fortran 2008 also allows the shorter things(1)%item = circle(...), but allocate(source=) is supported by every compiler.)

select type: recovering the concrete type

Sometimes you need a component that only an extension has. select type tests the dynamic type of a polymorphic object and, inside each branch, treats it as that type:

fortran · try it yourself
module vehicles
  implicit none
  type :: vehicle
    integer :: wheels = 4
  end type vehicle
  type, extends(vehicle) :: truck
    real :: payload_tonnes = 0.0
  end type truck
  type, extends(vehicle) :: bike
  end type bike
end module vehicles

program inspect
  use vehicles
  implicit none
  class(vehicle), allocatable :: fleet(:)
  integer :: i

  ! a polymorphic array: all elements share one dynamic type
  allocate(fleet, source=[truck(wheels=6, payload_tonnes=12.5), truck(wheels=4, payload_tonnes=3.0)])
  do i = 1, size(fleet)
    call show(fleet(i))
  end do
  call show(bike(wheels=2))
  call show(vehicle())

contains

  subroutine show(v)
    class(vehicle), intent(in) :: v
    select type (v)
    type is (truck)
      print '(a, i0, a, f5.1, a)', 'truck: ', v%wheels, ' wheels, ', v%payload_tonnes, ' t payload'
    type is (bike)
      print '(a, i0, a)', 'bike: ', v%wheels, ' wheels'
    class default
      print '(a, i0, a)', 'some vehicle with ', v%wheels, ' wheels'
    end select
  end subroutine show

end program inspect
truck: 6 wheels,  12.5 t payload
truck: 4 wheels,   3.0 t payload
bike: 2 wheels
some vehicle with 4 wheels

type is (truck) matches exactly that type; class is (vehicle) would match vehicle and every extension; class default catches everything else. Prefer type-bound procedures for behaviour that varies by type, and keep select type for the cases where you really need type-specific data.

Tip: class(*) is an unlimited polymorphic type: a variable of that type can hold a value of any type, including integers and strings. It is the basis for generic containers, and select type is the only way to get the value back out.

Test yourself

Which declaration creates a type dog that inherits from animal?

  1. type :: dog(animal)
  2. type, extends(animal) :: dog
  3. type :: dog inherits animal
  4. class dog : animal

What can a class(shape) variable hold?

  1. Only values of type shape
  2. A shape or any type extended from shape
  3. Any type at all
  4. Only pointers

In select type, what does type is (circle) match?

  1. circle and all its extensions
  2. Exactly the dynamic type circle
  3. Any shape
  4. Only pointers to circle