Fortran

Guide To Learn

Accessing derived type components

Once we have a class instance declared and initialized, in most cases we’ll want to access its components, often to read their values, sometimes to modify them. After all, if we use type components to store data that’s specific to the instance, there’s no use for it unless we can access it in some way.

To access derived type components, we’ll place a % symbol immediately after the type instance name, and before specifying the component name: some_person % name. The type instance name acts a lot like a namespace. If you had a regular variable declared as namesome_person % name wouldn’t conflict with it because it’s specific to the some_person instance.

Let’s say you want Bob from listing 8.3 to tell us more about himself; for example

Hi, I am Bob, a           32 year old Engineer

To print this to screen, you’d access the type components using the % syntax, and connect them with a few character string literals using the string concatenation operator //:

print *, 'Hi, I am ' // trim(some_person % name) // ', a ', &
  some_person % age, 'year old ' // some_person % occupation

Don’t worry about the awkward blank space in the middle of the greeting message. This is due to default formatting when mixing strings and integers in the print statement, like we saw back in chapter 6.

Similarly, we can access the ‘Field’ instance we initialized before using

print *, 'Initialized field ' // trim(h % name) // &
  ' with size ', h % dims

Note The Fortran derived type component access operator % is analogous to the dot operator (.) in C, Python, or JavaScript.

Accessing derived type components

Leave a Reply

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

Scroll to top