What are the main difference between TYPE and CLASS?

Dear all,

A quick question, modern Fortran have type and class, but,
What are the main difference between TYPE and CLASS ?

I feel that to some extent it seems they are interchangeable, is it?
I mean I define a type call it AAA, Now if I want a variable B with type AAA, in many cases it seems that, I can do both

type(AAA) :: B

and

class(AAA) :: B

Is it?

Thanks much in advance!

PS, I found a S.O topic,

But I do not fully understand the explanation.
Can someone explain the difference in some simple language? Thanks.

2 Likes

Well, please note you cannot “do both” generally.

With the polymorphic option i.e., the one with CLASS declaration the object needs to have either the ALLOCATABLE or the POINTER attribute when B is not a dummy argument:

class(AAA), allocatable :: B ! or class(AAA), pointer :: B

Perhaps this suffices as your “main difference”!!

But then should B be a dummy argument, then yes you can “do both”.

Anyways a book such as Modern Fortran Explained can better help answer such questions.

3 Likes

I wrote about this at Doctor Fortran in “Not My TYPE” - Doctor Fortran (stevelionel.com)

5 Likes

Intuitively, I guess it might be useful to think class(T) as something like type(<:T) or type(<= T) (= anything that is a subtype of T), in contrast to type(T) (= exactly the type T). So, with type(T) :: foo, we know how to generate actual data or an object on memory, but with class(T) :: foo, we don’t know what to generate actually (on memory)…

(The symbol <: seems to be explained here Subtyping - Wikipedia )

3 Likes