Home > front end >  Sending a pointer to a polymorphic/derived type
Sending a pointer to a polymorphic/derived type

Time:01-12

I'm encountering the following schematic problem:

  • A base class (defined as a regular type), let's call it base_a that defines a generic function
  • A derived type, let's call it class_a that inherits from base_a and implements that generic function
  • And generic class, let's call it class_b (see schematic code below)

My code saves the class base_a as a "type(base_a), pointer". I want to send this specific type to the generic class (class_b) and "save" it as a pointer component of base_a --- because in the future I will have other classes inheriting from base_a and i will want to pass them also to class_b, or pass them to class_b instead of class_a.

In other languages its suppose to be straightforward because class_a is base_a and base_a is saved in class_b, therefore i can create a function in class_b that recieves. But in Fortran I can't seem to pass class_a as a pointer, I may be confused because all of the 'type' and 'class' and 'pointer' definitions. It does work if I remove the pointer from Set_class function (below).

Can i even achieve this behavior in Modern Fortran? Is it even something i want? maybe i don't need pointers...

I will note, that i want to avoid making class_b familiar with class_a as much as possible (because once i keep adding types like class_a it will be pain to include them in class_b)

type, public :: base_a
contains 
    procedure, public :: Write1
...

type, public, extends(base_a) :: class_a
contains 
    procedure, public :: Write1 => Write_a
...


type, public :: class_b
    type(base_a), pointer :: really_class_a

 contains
     procedure, public :: Set_class
 ...

 subroutine Set_class(this, some_class)
      type(class_b), intent(inout) :: this
      type(base_a) , pointer(inout) :: some_class

      this%really_class_a => some_class
 end subroutine Set_class

 ... somewhere in main
 type(class_a), pointer :: class_a
 type(class_b), pointer :: class_b
 ...
 call this%class_b%Set_class(class_a)

Using intel oneAPI

I tried setting the following code but it didn't compile, it fails when i try and class the function Set_class, if i change the argument to be without a pointer it works.,

CodePudding user response:

I managed to find the problem.

In the function Set_class, the recieving object should not be defined as pointer, but as a target. In addition, really_class_a should be defined as class() and not type(). After these changes it work!

  • Related