0

I want to have a t2Class object in t1Class, with variables inside t2Class that can be used across t1Class member function. However, after allocating t2Class object in class function initialize, it cannot be used or deallocated when I want to use it in another t2Class function, giving the error of trying to access something undefined. I did not learn a lot for OOP in Fortran, so any help would be great.

main program:

program test
use t1Class_mod
implicit none 
class(t1Class),allocatable :: obj

allocate(obj)
print*, "obj%initialise"
call obj%initialise
print*, "obj%test1"
call obj%test1
end 

module with t1Class:

module t1Class_mod
use t2Class_mod
implicit none
type :: t1Class 
    class(t2Class),allocatable :: test
    contains
    procedure :: initialise => initialise
    procedure :: test1 => test1
    
    
end type t1Class
contains

subroutine initialise(this)
implicit none
    class(t1Class),intent(out) :: this
    allocate(this%test)
    this%test%n = 1
end subroutine initialise

subroutine test1(this)
implicit none
    class(t1Class),intent(out) :: this
    print*, "test1",this%test%n
end subroutine test1
end 

module with t2Class:

module t2Class_mod
implicit none
type :: t2Class 
    integer :: n
end type t2Class
contains
end 

EDIT, Solved: This is due to the intent(out) for "this" in class member function. Changing it to inout solves it.

DongAlpha
  • 15
  • 3
  • `this` in `test1` is `intent(out)`, so yes: it's undefined on entry. – francescalus Jul 01 '23 at 09:44
  • 1
    The linked question is a fairly general one which isn't directly the answer here: it's intended to show why `intent(out)` creates the behaviour you see. If you need more clarification or ideas how to do a particular thing, please [edit] your question with that detail. – francescalus Jul 01 '23 at 09:56
  • @francescalus Thank you for the reply. I have changed intent out to inout and it worked. I will also changed the question. – DongAlpha Jul 01 '23 at 10:05

0 Answers0