This is my second question related to Fortran (I use C++, so forgive me my way of thinking).
I want to use OOP, to say, derived type in Fortran whenever appropriate. In C++, you can use user defined constructor such as https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx
Here in Fortran, things are different. The first thing I tried is from here: https://www.ibm.com/developerworks/community/blogs/b10932b4-0edd-4e61-89f2-6e478ccba9aa/entry/object_oriented_fortran_user_defined_constructors2?lang=en
Link is broken, so I pasted it here:
module m
!...
interface base
module procedure new_base
end interface
contains
!...
function new_base(I)
integer, intent(in) :: I
type(base) new_base
allocate(new_base%data(I))
new_base%data = I
end function
!...
end module
The interface above defines a user-defined constructor for type base. It is used in a similar way to a structure constructor. It can even take argument keywords.
Then I found some other ways to do it. Here I listed a few approaches seemly to work but I only tested the first and second:
generic interface with the same name as the derived type they're supposed to construct, see link above;
use type-bound procedure (This is not even a "traditional" constructor)
MODULE mymod TYPE mytype Private INTEGER :: x CONTAINS PROCEDURE, PASS :: init END TYPE CONTAINS SUBROUTINE init(this, i) CLASS(mytype), INTENT(OUT) :: this INTEGER, INTENT(IN) :: i write(*,*) this%x IF(i > 0) THEN this%x = 1 ELSE this%x = 2 END IF write(*,*) this%x END SUBROUTINE init END PROGRAM test USE mymod TYPE(mytype) :: y CALL y%init(1) END PROGRAMuse Static Constructors or Structure Constructors (http://www.lahey.com/docs/lfenthelp/NLMOvUsInvConst.htm) But it appears that this is NOT for general Fortran http://www.lahey.com/docs/lfenthelp/NLMGSWhatIs.htm
So I haven't understood well enough what is most preferred and flexible approach to initialize/construct a derived type in practice, especially when I use nested derived type in development. I hope I can organize this topic with some help.