I am new to fortran and trying to implement a matrix class in it with the use of dynamic memory allocation and pointers. When I was trying to overload the assignment operator, I observed that the object members get reinitialized to zero on the entry to the assignment subroutine. Following is a simple program that reproduces the problem.
module matModule
implicit none
! Define the data kind for integer and real numbers
integer, private, parameter :: iKind = selected_int_kind(8), rKind = selected_real_kind(15,307);
type mat
integer(kind=iKind), public :: nrows,ncols,npage;
real(kind=rKind), pointer, public :: vals(:,:,:) => null();
contains
procedure, private, pass :: assign_scal_r
generic :: assignment(=) => assign_scal_r
end type mat
contains
subroutine assign_scal_r(this,value)
implicit none
real, intent(in) :: value
class(mat), intent(out) :: this
integer(kind=iKind) :: err
print *, loc(this%nrows), loc(this%ncols), loc(this%npage)
print *, associated(this%vals), this%nrows, this%ncols, this%npage
this%nrows = 1; this%ncols = 1; this%npage = 1;
if ( associated(this%vals) ) then
print *, "The array on the left is already allocated."
deallocate(this%vals, stat=err)
if (err /= 0) print *, "Error deallocating the variable."
end if
allocate(this%vals(this%nrows,this%ncols,this%npage), stat=err)
if (err /= 0) print *, "Error allocating the variable."
this%vals = value;
end subroutine
end module matModule
program main
use matModule
implicit none
type(mat) :: k
k = 5.0;
k = 1.0;
end program main
The output of this code is
140700383959168 140700383959172 140700383959176
F 0 0 0
140700383959168 140700383959172 140700383959176
F 0 0 0
Note that the output is generated from within the assignment subroutine. The variable 'k' in the main program goes through two assignment operations. It is understandable that the members are by default initialized to zero during the first assignment. However, the members contain 0 when the assignment subroutine gets executed second time. I am also printing the memory addresses of the members which, as per my understanding, show that the values of members get overwritten during the call to the assignment subroutine.
I am not sure if this is expected behavior. If it is an expected behavior, then my question is that does the pointer get deallocated automatically on the entry of the assignment subroutine? I have tried this on both Intel Fortran compiler and gfortran and both produce same results.
Pardon me if this whole problem is caused due to some stupid mistake I made in my code somewhere.