Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Derived Types and Pointers

Inheritance, Polymorphism and Abstract Types

Extend derived types with extends, override type-bound procedures, write abstract types with deferred procedures, and use class(*), select type and polymorphic arrays.

With type-bound procedures in place (previous lesson), Fortran adds the other two pillars of object-oriented design: inheritance (a new type builds on an existing one) and polymorphism (one variable holds objects of several related types, and the right procedure runs). This is how you model shapes, solvers or integrators that share an interface but differ in detail.

Extending a type

FORTRAN
module shapes
  implicit none

  type :: shape
    character(len=12) :: name = "shape"
  contains
    procedure :: area => shape_area
    procedure :: describe
  end type shape

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

  type, extends(shape) :: rectangle
    real :: w = 1.0, h = 1.0
  contains
    procedure :: area => rect_area        ! override
  end type rectangle

contains

  function shape_area(self) result(a)
    class(shape), intent(in) :: self
    real :: a
    a = 0.0
  end function shape_area

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

  function rect_area(self) result(a)
    class(rectangle), intent(in) :: self
    real :: a
    a = self%w * self%h
  end function rect_area

  subroutine describe(self)
    class(shape), intent(in) :: self
    print *, trim(self%name), " area =", self%area()
  end subroutine describe

end module shapes

extends(shape) gives circle every component and procedure of shape, plus its own. A type can extend one parent (single inheritance). The parent part is reachable as a component with the parent's name: c%shape%name, though c%name works as well.

procedure :: area => circle_area overrides the inherited binding. The overriding procedure's passed-object argument must be class(circle), and every other argument must match the parent's version in type, rank and intent.

Polymorphic variables

A variable declared class(shape) can hold a shape, a circle or a rectangle. The type that was actually allocated is its dynamic type:

FORTRAN
program poly_demo
  use shapes
  implicit none

  class(shape), allocatable :: s
  type(circle) :: c
  type(rectangle) :: r

  c = circle("circle", 2.0)
  r = rectangle("rectangle", 3.0, 4.0)

  s = c
  call s%describe()      ! calls circle_area through the binding

  s = r
  call s%describe()      ! now rectangle: area = 12.0
end program poly_demo

describe is written once for class(shape), yet self%area() runs the override that matches the object, decided at run time (dynamic dispatch). If your processor supports it, s = c allocates s with c's dynamic type through automatic reallocation; otherwise write allocate(s, source=c).

Python Stand-in: dynamic dispatch

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.

Abstract types and deferred procedures

Often the parent should never be instantiated: "shape" has no area of its own. Make it abstract and defer the procedure that children must supply:

FORTRAN
type, abstract :: shape
contains
  procedure(area_iface), deferred :: area
  procedure :: describe
end type shape

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

You cannot declare type(shape) :: x for an abstract type, but you can declare class(shape), allocatable :: x and allocate a concrete extension. Any extension that does not implement area is itself abstract, and the compiler will tell you. This is a clean way to define a contract, such as "every integrator has a step procedure".

The import :: shape line is needed because an interface body does not see its host's names otherwise.

classDiagram
    class shape {
      <<abstract>>
      +area() deferred
      +describe()
    }
    shape <|-- circle
    shape <|-- rectangle
    class circle { +r }
    class rectangle { +w, h }

Both concrete types implement area; describe is inherited as is.

Collections of mixed objects

You cannot make an array of class(shape) that holds different dynamic types: all elements of an array share one dynamic type. The standard workaround is a wrapper type with a polymorphic allocatable component:

FORTRAN
type :: shape_box
  class(shape), allocatable :: item
end type shape_box

type(shape_box) :: all(2)
allocate(all(1)%item, source=circle("circle", 1.0))
allocate(all(2)%item, source=rectangle("rectangle", 2.0, 5.0))
do i = 1, 2
  call all(i)%item%describe()
end do

Testing the dynamic type: select type

When you need to behave differently per type, use select type:

FORTRAN
select type (s)
type is (circle)
  print *, "radius", s%r
class is (rectangle)
  print *, "width", s%w
class default
  print *, "something else"
end select

type is matches exactly that type; class is matches it or any extension. Inside each block s has that more specific type, so you can reach its components. Prefer dynamic dispatch through bound procedures; select type is for the cases where the interface cannot cover it.

Unlimited polymorphism

class(*) can hold anything, much like void * in C or object elsewhere. You must use select type to get at the value:

FORTRAN
class(*), allocatable :: any
any = 3.5
select type (any)
type is (real)
  print *, "a real:", any
type is (integer)
  print *, "an integer:", any
end select

It is useful for containers, but you lose compile-time type checking.

Common mistakes

  • Overriding with a different argument list or intent; the compiler rejects it.
  • Declaring type(shape) for an abstract type.
  • Expecting one array of class(shape) to hold mixed types; use a wrapper.
  • Using select type everywhere instead of adding a bound procedure.
  • Forgetting import in an abstract interface body.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does type, extends(shape) :: circle create?

    extends builds a child type with all parent components and procedures, which it may add to or override.
  2. 2. What is a deferred procedure?

    Deferred bindings declare an interface but no implementation. Concrete extensions supply it.
  3. 3. Which declaration lets one variable hold a circle or a rectangle?

    class(...) declares a polymorphic variable whose dynamic type is a shape or any extension.
  4. 4. Which statement distinguishes dynamic types at run time?

    select type with type is and class is branches tests the dynamic type.

Summary

  • extends builds a child type; a binding is overridden with the same name and compatible interface.
  • class(t) variables are polymorphic; calls through them use dynamic dispatch.
  • abstract types and deferred bindings define contracts without implementations.
  • Arrays hold a single dynamic type: wrap polymorphic components for mixed collections.
  • select type inspects the dynamic type; class(*) accepts anything.

Next: Formatted output with edit descriptors