I am wondering if there is a constructor-like mechanism in Fortran for derived types, in such a way, that whenever an instance of a type is created, the constructor is called automatically. I read this question, but it was unsatisfactory to me.
Schematic example for completeness:
module mod
integer :: n=5
type array
real, dimension(:), allocatable :: val
contains
procedure :: array()
end type
subroutine array(this)
allocate(this%val(n))
end subroutine
end module
Now when I create an instance of type(array) :: instance
I'd like the constructor array(instance)
to be called automatically without any extra call array(instance)
in the code added manually.
I found some promising information on this site, but nowhere else: It specifies a constructor-like mechanism with the type-bound procedure declared initial,pass :: classname_ctor0
. What standard is this? ifort
in version 16 won't compile the example posted there and I have no standard available.
An 'initial' subroutine is not, unlike a final subroutine, part of a Fortran standard.
In a derived type certain components may have initial values, set by default initialization, such as
type t
integer :: i=5
end type t
type(t) :: x ! x%i has value 5 at this point
However, allocatable array components (along with some other things) may not have default initialization and always start life as unallocated. You will need to have a constructor or some other way of setting such an object up if you wish the component to become allocated.
In the case of the question, one thing to consider is the Fortran 2003+ parameterized type:
type t(n)
integer, len :: n
integer val(n)
end type
type(t(5)) :: x ! x%val is an array of shape [5]
This naturally isn't the same this as an allocatable array component with an "initial" shape, but if you just want the component to be run-time initial customizable shape this could suffice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With