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

Sourced allocation for polymorhic variables

Jon_D
New Contributor II
367 Views
Hello,

I am trying to figure out objected oriented programming with Fortran. Below is my simple test code. Shape is the base class with color attribute, rectangle and cirle classes extend the shape class and add dimensions (length and width for rectangle, radius for circle). The source code for individual classes are not included.

The code compiles fine. But when I allocate the testsh variable using either shape or rectangle as the source in the subroutine, I only get the color attribute regardless of the actual type. In other words, when it is allocated using rectangle as the source, length and width does not get cloned, only color from shape class. Is this the expected behaviour? I thought the whole point of using polymorhic variables is that they can be morphed into a parent or a child type without data loss.

Thanks for any help!

[fortran]subroutine test(sh,testsh) use shape_class use rectangle_class use circle_class implicit none class(shape) :: sh class(shape),allocatable :: testsh if (allocated(testsh)) deallocate (testsh) allocate (testsh , source=sh) end subroutine test program main use shape_class use rectangle_class use circle_class implicit none interface subroutine test(sh,testsh) use shape_class use rectangle_class use circle_class implicit none class(shape) :: sh class(shape),allocatable :: testsh end subroutine test end interface type(shape) :: sh type(rectangle) :: rect type(circle) :: cir class(shape),allocatable :: testsh sh = newshape(1) rect = rectangle(1,2.,3.) cir = circle(1,5.) call test(sh,testsh) call test(rect,testsh) end [/fortran]
0 Kudos
2 Replies
IanH
Honored Contributor III
367 Views
Could you attach the source for the *_class modules too?

What are you using to determine whether the other attributes get copied (your program as provided generates no output). Note that if you are inspecting things using the debugger then it tells fibs about polymorphic variables.
0 Kudos
Jon_D
New Contributor II
367 Views
Thanks! I was using the debugger to inspect the variable. When I print the components, they come out fine.
0 Kudos
Reply