Correct usage of polymorphic arrays

Viewed 27

I am stuck on the correct coding of polymophic arrays in Fortran.

Here my not working code:

program PolyArray

implicit none

type basetype
character(len=1) :: my_name
end type basetype

type, extends(basetype) :: exttype1
    character(len=1) :: my_name_ext1
end type exttype1

type, extends(exttype1) :: exttype2
    character(len=1) :: my_name_ext2
end type exttype2

type arraytype
    class(basetype), allocatable :: comp
end type arraytype

type(basetype) :: a
type(exttype1) :: b
type(exttype2) :: c
type(arraytype), dimension(3) :: ary
integer :: i

allocate (basetype::ary(1)%comp)
allocate (exttype1::ary(2)%comp)
allocate (exttype2::ary(3)%comp)

ary(1)%comp%my_name = 'a'
ary(2)%comp%my_name_ext1 = 'b'
ary(3)%comp%my_name_ext2 = 'c'

write(*,*) ary(1)%comp%my_name, ary(2)%comp%my_name_ext1, ary(3)%comp%my_name_ext2

end program PolyArray

The compiler (gfortran 10.2.0 ) complains with:

 Error: 'my_name_ext1' at (1) is not a member of the 'basetype' structure; did you mean 'my_name'?

I find this a bit odd since I am explicitly allocating comp with the correct extended type.

0 Answers
Related