Programming Languages on Power

Power Programming Languages

IBM Power, including the AIX, IBM i, and Linux operating systems, support a wide range of programming languages, catering to both traditional enterprise applications and modern development needs.


#Power

 View Only
Expand all | Collapse all

Copying an extended derived type into its base (parent) type

  • 1.  Copying an extended derived type into its base (parent) type

    Posted Tue October 31, 2017 01:17 PM

    Originally posted by: hemangh


    Is there a way to "painlessly" copy those elements of an extended type that are shared with its base type into a new base type array?

    For example I want to copy a everything in the type (truck) :: A into a type(vehicle)::B, except for anual_milage. I don't want to go over each element of type A and pick and choose.

     

          module types
           implicit none

            type :: vehicle
               integer :: wheels
               character(len=6),allocatable,dimension(:)  :: service_date
            end type vehicle
            
            type,extends(vehicle) :: truck
              real, allocatable, dimension(:,:) :: anual_miles
            end type truck

            type track
              
              class(vehicle), pointer :: object => null()

            end type track


           end module

           program test_alloc
            use types
            implicit none

            
            type(truck)::A  
            type(vehicle) :: B

            A%wheels = 8
            allocate(A%service_date(2))
            A%service_date(1)='May16'
            A%service_date(2)='Sep16'
            allocate(A%anual_miles(10,10:17))
            A%anual_miles = 0.0
            A%anual_miles(1,10) = 3067.1
              
            call fill_x(B,A)        

           end program test_alloc


           subroutine fill_x(B,A)
            use types
            class(vehicle), target      :: A
            class(vehicle), allocatable :: B

    !       allocate(B, mold=A)
    !       what should go here?
            
           end subroutine

     


    #C/C++andFortran
    #Fortran-Cafe-for-AIX


  • 2.  Re: Copying an extended derived type into its base (parent) type

    Posted Wed November 01, 2017 11:40 AM

    Originally posted by: Rafik_Zurob


    All extended types have a parent component that gives you access to the fields of the parent.  The parent component's name is the name of the base type.  So instead of calling fill_x, you can just have:

    B = A%vehicle
    

    #Fortran-Cafe-for-AIX
    #C/C++andFortran


  • 3.  Re: Copying an extended derived type into its base (parent) type

    Posted Wed November 01, 2017 01:50 PM

    Originally posted by: hemangh


    Thank you, that is what I ended up figuring out after a lot of head banging.

    allocate(B, source=A%vehicle) would do  the job of allocation and copying if B is type(vehicle)


    #C/C++andFortran
    #Fortran-Cafe-for-AIX