Search code examples
fortranfortran2008

Structure constructor with private component


I have defined a structure with a private component in following example:

module mtypes
    implicit none

    type mytype
        integer, private :: nr
    end type

end module mtypes

program main

    use mtypes
    type(mytype) :: t1

    t1 = mytype(1)
    print *, t1

end program main

The structure constructor is called with 1 as an argument. For my understanding this should not be possible, because nr is private. However, this is compiled by Intel(R) Visual Fortran Compiler XE 14.0.5.239 [IA-32], but not with gfortran 4.9.3 using cygwin. Moreover the print statement shows the value of nr in the output. Is it valid Fortran to define a structure with a private component in this way using the latest standard? Or is this a bug of the intel compiler?


Solution

  • In the draft of Fortran 2008, implicit (that is, those that comes from the derived type definition) structure constructors are detailed in 4.5.10. One constraint given there is

    The type name and all components of the type for which a component-spec appears shall be accessible in the scoping unit containing the structure constructor.

    As the component nr is not accessible in the main program this constraint is violated by having nr as a component-spec. Using this implicit structure constructor in the module would be fine, as would having default initialization for the private component.

    nagfor also complains about your code example for this reason.

    On the print statement, this is clearly not valid, and ifort 15 complains about that. For t1 to appear in an output list you must use a define output procedure.