Fortran

Guide To Learn

Your first type-bound method

Looking back at our derived-type hello world program from listing 8.2, the subroutine we’ll bind to the type is the greeting subroutine, as shown here:

subroutine greet(self)
  class(Person), intent(in) :: self                             ❶
  print *, 'Hello, my name is ' // trim(self % name) // '!'     ❷
end subroutine greet

❶ The input argument will be the type instance itself.

❷ We can access type components from here.

Here we have another new syntax element–class. Declaring class(Person) instead of type(Person) allows any type that’s extended (derived) from Person to be passed to this subroutine. For now, you don’t need to know more about class than this. Just think of class(Person) as a more general form of type(Person). This argument we’ll call self, to refer to the type instance itself. This can be any word you want–some people like to use this, others prefer some other keyword–it’s totally up to you. Once we have the instance passed to the procedure, we can reference any of its components using the self % syntax.

The second step involves the actual binding–attaching the procedure to the type so that it comes with it wherever the type instance is used. We’ll bind the procedure inside the derived type definition, immediately after the contains statement:

type :: Person
  ...
contains                               ❶
  procedure, pass(self) :: greet       ❷
end type Person

❶ Separates the components and the methods

❷ Binds this procedure and passes the type as the argument self

Notice that binding a procedure to the type is somewhat similar to overriding a default type constructor like we did in section 8.2.6. One key difference is that for a type-bound procedure, the type must be declared as an intent(in) (if read-only) or intent(in out) argument, rather than being the function result. The other difference is that the method is bound in the contains section of the type definition, instead of a separate interface that’s used for custom constructors.

Your first type-bound method

Leave a Reply

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

Scroll to top