chapter ten

10 Overloading operators for derived types

 

This chapter covers:

  • Overloading operators in a minimal countdown app
  • Validating user input
  • Synchronization on assignment in the tsunami simulator

Almost any app working with real-world data, or any program more complex than a toy model, will use derived types (classes) to handle abstract data. Fortran’s intrinsic operators for arithmetic (+, -, *, /, **) and comparison (==, /=, >=, , >, <) are available out of the box for intrinsic numeric (integer, real, complex) but not for derived types. For example, to keep track of calendar date and time in an app, you’d need to compare, add, and subtract datetime instances (data structures that represent date and time). This is where derived types (Chapter 6) and generic procedures and custom operators (Chapter 7) come together to form a powerful feature of the language: Overloading intrinsic operators for derived types. This will allow you to define what the intrinsic (and custom) operators mean for any derived type, and in a way extend the syntax of the language.

10.1  Happy Birthday! A countdown app

10.1.1  Some basic specification

10.1.2  Implementation strategy

10.2  Getting user input and current time

10.2.1  Your first datetime class

10.2.2  Reading user input

10.2.3  Getting current date and time

10.3  Calculating the difference between two times

10.3.1  Modeling a time interval

10.3.2  Overloading the subtraction operator

10.3.3  Time difference algorithm

10.3.4  The complete program

10.4  Overloading operators in the Tsunami simulator

10.4.1  A refresher on the Field class

10.4.2  Implementing the arithmetic for the Field class

10.4.3   Syncing parallel images on assignment

10.5  Answer key

10.5.1  Exercise 1: Validating user input

10.7  Summary