Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Array of polymorphic objects

OP1
New Contributor III
1,125 Views
Just graduated to IVF 11.1.070 and trying towrap my head around some of the new concepts related to polymorphism.

Is it possible to declare an allocatable array of components, where each component belongs to the same class but could be of different types within that class?

In pseudo code:

Declarea parent type P.
Extend P with child types C1 and C2.
Declare an allocatable array of objects of class P.
Allocate each element of P to the proper type (C1 or C2).

Thanks for any help on this - or for pointers to useful reference examples/material.

Olivier
0 Kudos
5 Replies
Steven_L_Intel1
Employee
1,125 Views
Yes, this is possible. But I strongly recommend using a more recent compiler as we have fixed many issues with polymorphism since 11.1.
0 Kudos
Andrew_Smith
Valued Contributor I
1,125 Views
Steve, could you show an example as I can not see how this would work as you describe without some additional structure. Simple arrays must all be the same type I think even if the type is extended.
0 Kudos
Steven_L_Intel1
Employee
1,125 Views
Andrew,

The request was for an array of components - which I took to mean an array of derived type. Here's an example.

[fortran]    program PolyArray

    implicit none
    
    type basetype
    end type basetype
    
    type, extends(basetype) :: exttype1
    end type exttype1
    
    type, extends(exttype1) :: exttype2
    end type exttype2
    
    type arraytype
        class(basetype), allocatable :: comp
    end type arraytype
    
    type(arraytype), dimension(3) :: ary
    integer :: i
    
    allocate (basetype::ary(1)%comp)
    allocate (exttype1::ary(2)%comp)
    allocate (exttype2::ary(3)%comp)
    
     do i=1,3
        select type (st=>ary(i)%comp)
        type is (basetype)
            print 101,i,"basetype"
        type is (exttype1)
            print 101,i,"exttype1"
        type is (exttype2)
            print 101,i,"exttype2"
        class default
            print 101,i,"unknown"
        end select
  101    format ("The dynamic type of ary(",i0,")%comp is ",A)
        end do
        
    end program PolyArray[/fortran]
and when I build and run this I get:

[plain]The dynamic type of ary(1)%comp is basetype
The dynamic type of ary(2)%comp is exttype1
The dynamic type of ary(3)%comp is exttype2[/plain]
For some odd reason the forum is removing the 101 label on the format - grr. If you "View Plain" it should be there.
0 Kudos
Andrew_Smith
Valued Contributor I
1,125 Views
Thanks Steve, that is similar to the way I have tackled it i.e by containing the polymorphic components inside a common wrapper object
0 Kudos
OP1
New Contributor III
1,124 Views

Yes, thanks Steve for your example - this is what I was looking for.

Olivier

0 Kudos
Reply