next up previous contents
Next: Arrays and Derived Types Up: Derived Types Previous: Derived Types   Contents

Defininig Derived Types

Compound entities (similar to C ``structures'', or to Pascal ``records'') can be defined in F90; they are known as derived types.

For example, the three real coordinates of a 3D Point can be packed into a single variable. First, we define a new type in a derived-type statement

type Point
   real :: x,y,z 
end type Point

An object of type Point can be declared in a type declaration statement

type(Point) :: A, B
To select individual components of a derived type object, we use the % operator; for example
A%x = 1.0
A%y = 2.0
A%z = 3.0 
assigns the values 1,2,3 to the individual components (coordinates) of A.

As an alternative to component-by-component assignment, it is possible to use a derived type constructor to assign values to the whole object. The derived type constructor is the type name followed by a paranthesised list of values, which will be assigned to the individual components. For example, the coordinate assignment of A can be solved using

A = Point( 1.0, 2.0, 3.0 )

Assignment between two objects of the same derived type is intrinsically defined (and is equivalent to component-by-component assignment). For example, the statement

B = A
has the effect of setting the x,y,z components of pt_B to 1,2 and respectively 3.

Note that, since F90 does not imply any form of storage association, there is no reason to suppose that objects of type Point occupy 3 contiguous REAL storage locations.

A new derived type can contain another derived type as one of its components; the derived type of the components must have already been declared or must be the type currently being declared. As an example of ``supertype'' consider

type Sphere
  type(Point) :: center 
  real :: radius
end type Sphere 
type(sphere) :: bubble 
bubble%radius = 1.0
bubble%center%x = 0.2 
bubble%center%y = 0.4 
bubble%center%z = 0.6 
bubble = Sphere( Point(0.2,0.4,0.6), 1.0 )
Finally, derived objects can be used in I/O statements similarly to the intrinsic objects. The statement
print*, bubble
is equivalent to
print*, bubble%center%x, bubble%center%y, bubble%center%z, bubble%radius
%


next up previous contents
Next: Arrays and Derived Types Up: Derived Types Previous: Derived Types   Contents
Adrian Sandu 2001-08-26