Polymorphism and SELECT TYPE
Inheritance gives a child its parent's components and bindings. Polymorphism is the other half: a variable declared with a class() type may hold a value of any type below it, and a binding call through that variable runs the version that belongs to the value it actually holds. This lesson overrides a binding in a child, calls it through a polymorphic variable and sees two different results, then looks at the value with select type to read the components only the child has.
Overriding a binding
The child declares a binding with the same name as one it inherits, and its own procedure takes over for the child. point3 binds norm to point3_norm, which adds the square of z; a class(point) call on a point3 value runs that one. The binding of a child must keep the interface of the parent's: same name, and a passed-object dummy the compiler accepts as an extension of the parent one.
The file poly.f90:
module shapes
implicit none
private
public :: point, point3, describe
type :: point
real :: x = 0.0
real :: y = 0.0
contains
procedure :: norm => point_norm
end type point
type, extends(point) :: point3
real :: z = 0.0
contains
procedure :: norm => point3_norm
end type point3
contains
function point_norm(self) result(r)
class(point), intent(in) :: self
real :: r
r = sqrt(self%x**2 + self%y**2)
end function point_norm
function point3_norm(self) result(r)
class(point3), intent(in) :: self
real :: r
r = sqrt(self%x**2 + self%y**2 + self%z**2)
end function point3_norm
subroutine describe(p, label)
class(point), intent(in) :: p
character(len=*), intent(in) :: label
select type (v => p)
type is (point3)
print '(a,a,3f6.1,a,f8.3)', trim(label), ' point3', v%x, v%y, v%z, ' norm = ', v%norm()
class is (point)
print '(a,a,2f6.1,a,f8.3)', trim(label), ' point ', v%x, v%y, ' norm = ', v%norm()
class default
print '(a,a)', trim(label), ' unknown type'
end select
end subroutine describe
end module shapes
program polydemo
use shapes
implicit none
class(point), allocatable :: obj
type(point3) :: q
q = point3(1.0, 2.0, 2.0)
print '(a,f8.3)', 'static q%norm() = ', q%norm()
allocate(point3 :: obj)
obj = q
print '(a,f8.3)', 'dynamic obj%norm() = ', obj%norm()
call describe(obj, 'obj:')
deallocate(obj)
allocate(point :: obj)
obj = point(3.0, 4.0)
print '(a,f8.3)', 'dynamic obj%norm() = ', obj%norm()
call describe(obj, 'obj:')
end program polydemo
gfortran -Wall -Wextra -std=f2018 poly.f90 -o poly
./poly
static q%norm() = 3.000
dynamic obj%norm() = 3.000
obj: point3 1.0 2.0 2.0 norm = 3.000
dynamic obj%norm() = 5.000
obj: point 3.0 4.0 norm = 5.000
The first line is a static call: the compiler knows q is a point3 and binds point3_norm directly. The second and the fourth are the same statement with a different dynamic type in obj, and they give three and five: that is the dispatch, made by a table the compiler attached to the type.
Dynamic dispatch
Dispatch happens when the declared type is polymorphic and the binding is overridden. A variable declared type(point3) is not polymorphic, so its calls are static; a dummy declared class(point) or a variable declared class(point), allocatable is. The call p%norm() inside describe is the interesting one: it is compiled once, and the same instruction finds the right procedure for a point and for a point3.
The cost is one indirect call, the same as a procedure pointer, and it cannot be inlined. A design that puts a virtual call inside the innermost loop pays for it in every iteration; a design that puts it at the level of "handle this item" pays once per item, which is what the call is for.
SELECT TYPE
A class(point) dummy cannot name %z, so the child's own components are reached with select type. The block takes an associate name, select type (v => p), and each branch declares what v is: type is (point3) matches exactly a point3, class is (point) matches a point or any type below it, and class default catches everything else.
Inside a branch the name has that declared type, so v%z compiles in the first branch and not in the second. The order of the branches matters, exactly as in select case: the first match wins, which is why type is (point3) comes before class is (point).
ALLOCATE with a type
allocate(point3 :: obj) gives the polymorphic variable a dynamic type explicitly: obj is declared class(point) and holds a point3. allocate(obj, source=q) would do the same and copy the value in one statement, and mold=q would allocate without copying. Deallocating and allocating again with point changes the dynamic type of the same variable, which is the second half of the run.
Assignment is the other way to set a dynamic type: obj = q reallocates obj to the type and shape of q when they differ. Both routes need the target to be allocatable, because a polymorphic variable that is not allocatable cannot change its dynamic type after it is declared.
Static and dynamic
A useful habit is to ask of every %call whether the declared type is polymorphic. If it is a type(t) variable or dummy, the call is static, the compiler may inline it, and overriding in a child changes nothing for that call. If it is class(t), every call through it is a dispatch, whether or not any child exists today.
That is the price of the feature: a library that declares class(t) dummies everywhere so that a future child can plug in pays an indirect call everywhere today. Declaring type(t) in the hot path and class(t) at the boundaries is the usual compromise.
A child component through the parent
The compiler enforces the rule that a class(point) name sees only the parent part:
program badselect
implicit none
type :: point
real :: x = 0.0
real :: y = 0.0
end type point
type, extends(point) :: point3
real :: z = 0.0
end type point3
type(point3) :: q
q = point3(1.0, 2.0, 3.0)
call show_z(q)
contains
subroutine show_z(p)
class(point), intent(in) :: p
print *, p%z
end subroutine show_z
end program badselect
gfortran -Wall -Wextra -std=f2018 err.f90 -o err
err.f90:21:16:
21 | print *, p%z
| 1
Error: 'z' at (1) is not a member of the 'point' structure
The message is exactly right: z is not a member of point, and the declared type is what a component reference is checked against. The fix is the select type of the first program, and there is no other.
The rules that matter
A polymorphic variable that changes its dynamic type must be allocatable, a pointer, or a dummy with intent(out). An array of class(t) is allocatable as a whole, but an element of it is not, so a heterogeneous collection is a type with an allocatable polymorphic component rather than an array of the parent type. A binding is overridden only when the child declares the same name, and a binding that is non_overridable may not be.
One behaviour of this build is worth knowing before a heterogeneous collection is written. An element of an array of a type with an allocatable polymorphic component, filled with a plain assignment (list(1)%obj = point(...)) and then passed to a class(point) dummy, crashed with a segmentation fault, while allocate(list(1)%obj, source=point(...)) filled the same component and ran, and so did a scalar variable of the same type. That is why the program above holds one polymorphic variable at a time; a collection built this way should be tested on the compiler it will run on.
Exercises
- Remove the norm binding from point3 and run the program again. Which lines change, and why?
- Add a branch class is (point3) before type is (point3). Is the program still correct?
- Declare obj as class(point), pointer and allocate it with allocate(point3 :: obj). What has to be added before the program ends?
- Call describe on a type(point) value declared statically. Which branch runs, and does the call inside it dispatch?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What makes a binding call dispatch at run time?
Answer
A polymorphic declared type and an overridden binding
Both a class() declaration and an override are needed.
-
What is the difference between
type isandclass isin SELECT TYPE?Answer
type is matches exactly; class is also matches extensions of that type
A class is branch also catches the children of the named type.
-
What does this program print?
module m implicit none type :: a contains procedure :: v => a_v end type a type, extends(a) :: b contains procedure :: v => b_v end type b contains integer function a_v(self) class(a), intent(in) :: self a_v = 1 end function a_v integer function b_v(self) class(b), intent(in) :: self b_v = 2 end function b_v end module m program p use m implicit none class(a), allocatable :: o allocate(b :: o) print *, o%v() end program pAnswer
2
The dynamic type is b, so b_v runs.
-
Why does
allocate(point3 :: obj)need obj to be allocatable?Answer
A polymorphic variable can only change its dynamic type if it can be allocated
The dynamic type of a non-allocatable variable is fixed at declaration.
-
What does
select type (v => p)give the branches?Answer
A name v whose declared type each branch decides
The associate name takes the type of the matched branch.
-
What does gfortran report for
p%zinside a class(point) dummy?Answer
Error: 'z' is not a member of the 'point' structure
A component reference is checked against the declared type.
-
What may a polymorphic variable that changes dynamic type NOT be?
Answer
A plain non-allocatable, non-pointer variable
Its type is fixed at declaration unless it can be reallocated.
-
What is the run-time cost of a dispatched call?
Answer
One indirect call, which cannot be inlined
The implementation is found through a table at the call.
-
Why is a heterogeneous list a type with an allocatable polymorphic component?
Answer
An element of a class array is not allocatable, so it cannot change type
Only an allocatable can hold values of different dynamic types.
-
What did this build do with an array element whose allocatable polymorphic component was filled by assignment and then passed as an argument?
Answer
It crashed with a segmentation fault; allocate with source= instead worked
The lesson states the observed crash and the route that worked.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev