So far in this chapter, we’ve covered the essentials of Fortran derived types:
- Defining a type and its components
- Declaring and initializing a type instance
- Writing a custom type constructor function
- Turning procedures into type-bound methods
- Accessing components and invoking type-bound methods
Fortran offers much more in this realm, such as extending derived types (known as inheritance in object-oriented programming), and abstract types whose methods can do different things depending on the concrete type of the instance. See the “Further reading” section at the end of this chapter to learn more about these concepts.
Before we move on to the final steps in refactoring the tsunami simulator, I have one more exercise for you to complete (“Exercise 2” sidebar), which will tie derived types together with the power of elemental procedures that we learned about in section 3.5.
Exercise 2: Invoking a type-bound method from an array of instances
In section 3.5, you learned about elemental procedures, which you define as if operating strictly on an input scalar (nonarray), but can be readily used on arrays of any size or dimension. Can you rewrite our program from listing 8.2, such that we can define an array of Person instances and then invoke the greet method on that array? For example
call people % greet()
should output the following to the screen:
Hello, my name is Jill!
Hello, my name is James!
Hello, my name is Allison!
You can find the solution in the “Answer key” section near the end of this chapter.
Hint: Recall the use of impure elemental attributes from chapter 3.