- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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]
Link Copied
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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]
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
thank you, Steve!
Shihao
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page