I am programming in Fortran and I need to create an object class that has a dynamic vector as an attribute. Here is a minimal example of what I am trying to achieve.
MODULE my_class
PRIVATE
PUBLIC my_object
! define my object with a dynamic attribute
TYPE my_object
private
integer:: size;
real, allocatable:: tab(:); ! here the dynamic vector
CONTAINS
private
final:: destructor;
END TYPE my_object
! define an interface for object constructor
INTERFACE my_object
module procedure:: constructor;
END INTERFACE my_object
CONTAINS
! define constructor
FUNCTION constructor(size) RESULT(obj)
integer, intent(in):: size;
type(my_object):: obj;
obj%size= size;
allocate(obj%tab(size))
END FUNCTION constructor
! define destructor
SUBROUTINE destructor(this)
class(my_object):: this;
if (allocated(this%tab)) deallocate(this%tab)
END SUBROUTINE
END MODULE my_class
But I am not sure that is the proper way to do it. Is there not a risk of memory leaking with this implementation in case of multiple initializations? With this code for example :
PROGRAM test
USE my_class
IMPLICIT NONE
type(my_object):: obj;
obj= my_object(1000);
obj= my_object(3000);
END PROGRAM test
Has the obj%tab of the first instance been properly deallocated?
Or should I reimplement the equal operator?
Thanks for helping me to find out how Fortran deals with this.