Fortran

Guide To Learn

Providing default values for derived type components

Fortran allows you to set a default (initial) value of any component in the derived type definition itself. The following listing provides an example.

type :: Person
  character(len=20) :: name
  integer :: age
  character(len=20) :: occupation = 'Programmer'     ❶
end type Person

❶ Sets the default value

With the Person type defined like this, only the name and age components are required to be passed to the constructor. If the occupation argument is given, it will override the default value:

some_person = Person('Allison', 28)
print *, some_person % occupation                   ❶
other_person = Person('Richard', 32, 'Accountant')
print *, other_person % occupation                  ❷

❶ Will print “Programmer”

❷ Will print “Accountant”

Obviously, this approach works only for components that have meaningful default values, which is not always the case. For example, if you wanted to have a Person type that you could initialize as some_person = Person(), and set the component values at a later time, you’d initialize all its components in the type definition block:

type :: Person
  character(len=20) :: name = ''         ❶
  integer :: age = 0                     ❷
  character(len=20) :: occupation = ''   ❶
end type Person

❶ Sets name to an empty string

❷ Sets age to an invalid value, such as zero

Note that in this case, both the name and occupation component will be character strings of length 20 but will be initialized to blank characters (empty spaces). For age, a zero or a negative number could serve as the default value if an argument isn’t provided to the constructor.

As I mentioned earlier, the other, more general approach is to write a custom derived type constructor function to override the default one. This will become important whenever we want to work with the input parameters, such as validate the input, allocate dynamic data, or call any number of other procedures, before returning the new instance to the caller.

Providing default values for derived type components

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top