Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28520 Discussions

allocatable extended derived data type

wang__shihao
Beginner
235 Views

I am coding a program with allocatable derived datatype like the following code.

my problem is that after allocating test_array using type child, the data is not well allocated. It turns out that the allocated test_array only has integer A, without integer B.

Are there any way to allocate such an array test_array with all data from parent and child data type?

Thanks!

program test
use p_c
call data_allocator
!write(*,*) test_array(2)%B


module p_c
type,abstract,public::parent
integer::A=1
end type parent

type,extends(parent)::child
integer::B=2
end type child

class(parent),allocatable,dimension(:)::test_array
contains

subroutine data_allocator
allocate(child::test_array(5))

end subroutine data_allocator

end module p_c

end program test

0 Kudos
1 Solution
Steven_L_Intel1
Employee
235 Views

It does work, but your program isn't correct in how it sees it. In the commented out WRITE, the compiler uses the "declared type", which is parent, and that doesn't have a B component. You have to do it this way:

[fortran]
module p_c
type,abstract,public::parent
integer::A=1
end type parent

type,extends(parent)::child
integer::B=2
end type child

class(parent),allocatable,dimension(:)::test_array
contains

subroutine data_allocator
allocate(child::test_array(5))

end subroutine data_allocator

end module p_c
program test
use p_c
call data_allocator
select type(test_array)
    type is (child)
    write(*,*) test_array(2)%B
    class default
    write (*,*) "Oops!"
    end select

end program test
[/fortran]

View solution in original post

0 Kudos
2 Replies
Steven_L_Intel1
Employee
236 Views

It does work, but your program isn't correct in how it sees it. In the commented out WRITE, the compiler uses the "declared type", which is parent, and that doesn't have a B component. You have to do it this way:

[fortran]
module p_c
type,abstract,public::parent
integer::A=1
end type parent

type,extends(parent)::child
integer::B=2
end type child

class(parent),allocatable,dimension(:)::test_array
contains

subroutine data_allocator
allocate(child::test_array(5))

end subroutine data_allocator

end module p_c
program test
use p_c
call data_allocator
select type(test_array)
    type is (child)
    write(*,*) test_array(2)%B
    class default
    write (*,*) "Oops!"
    end select

end program test
[/fortran]

0 Kudos
wang__shihao
Beginner
235 Views

thank you, Steve!

Shihao

0 Kudos
Reply