Skip to content
Object-Oriented Fortran
step 1/5

Reading — step 1 of 5

Learn

~2 min readOOP, Parallel, Numerical

Modern Fortran (2003+) has full OO: type-bound procedures, inheritance, polymorphism, abstract types.

Type-bound procedures

type :: shape
    real :: x, y
contains
    procedure :: move
end type

contains
    subroutine move(self, dx, dy)
        class(shape), intent(inout) :: self
        real, intent(in) :: dx, dy
        self%x = self%x + dx
        self%y = self%y + dy
    end subroutine

Calling: call s%move(1.0, 2.0)self is implicit.

class(shape) vs type(shape):

  • type(shape) — exactly this type
  • class(shape) — this type OR any extending type — enables polymorphism

Inheritance

type, extends(shape) :: circle
    real :: radius
contains
    procedure :: area
end type

contains
    function area(self) result(a)
        class(circle), intent(in) :: self
        real :: a
        a = 3.14159 * self%radius**2
    end function

circle automatically has x, y, AND radius. The area is specific to circle.

Abstract types

type, abstract :: base
contains
    procedure(area_interface), deferred :: area
end type

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

Concrete subtypes MUST implement area. The compiler enforces this.

Polymorphism

subroutine print_area(s)
    class(base), intent(in) :: s     ! accepts any base subtype
    print *, "area: ", s%area()
end subroutine

s%area() dispatches to the actual runtime type — circle's area, square's area, etc.

select type

select type (s)
type is (circle)
    print *, "circle radius:", s%radius
class is (shape)
    print *, "shape at", s%x, s%y
class default
    print *, "unknown"
end select

Like Java's instanceof chain — runtime type discrimination.

Why Fortran has OOP

Fortran 2003 added OOP partly to compete with C++ for scientific computing. Many modern climate, fluid dynamics, and physics codes are OOP-style Fortran — clearer than 30-year-old common-block-heavy programs.

Caveats

  • Compilers vary in OOP completeness (gfortran is good, ifort is excellent)
  • Performance: virtual dispatch is slightly slower than monomorphic — usually fine
  • OOP can make Fortran feel un-Fortran-like — many traditional users avoid it

Discussion

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

Sign in to post a comment or reply.

Loading…