Understanding polymorphism

Understanding polymorphism

I am trying to learn some object oriented programming and have written a small program that I copied from a C++ book. The program uses inheritance and defines three types. The base type is INSTRUMENT, this is extended to the two types THERMOMETER and BAROMETER. The types have type bound procedures: INSTRUMENT has  SETNO, GETNO, SETLOCATION, GETLOCATION and WRITE. The two meters have SET, GET and WRITE. All this is defined in a module. The main program contains pointers of class INSTRUMENT and variables of type THERMOMETER and BAROMETER, these have the target attribute.
The trouble starts with the pointers. The code looks like this:
pointer => variable ! of type THERMOMETER
CALL pointer % WRITE() ! This works, thermometer data is written, but
CALL pointer % GET(temp) ! does not work. You have to put it in a SELECT TYPE construct. Why?
It seems to me that by using SELECT TYPE one is inquiring about which dynamic type is beeing used. The compiler knows the answer so why does one have to ask? Or, am I misunderstanding all this? If we need to use select type every time we are using a pointer of a base class I think the programming will be very cumbersome. Anyway, we sure need a textbook in Fortran on OOP.
Thanks for any help. Attached is the complete program.



Downloadapplication/octet-stream f-2003-test-9.f906.75 KB
3 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

I think the answer is that with Fortran everything needs to be deducible by the compiler. Pointer association is done at runtime so that in the statement below the compiler doesn't know that P_A is associated with an object of type(thermometer) - it is declared as a pointer to an object of type(instrument); you could reassign it immediately to an object of type(barometer) as below. If you put the call inside a 'select type' construct then the compiler can arrange for the correct subroutine to be called.

P_A => B1

subroutine WRITE has a base class (INSTRUMENT) implementation, while GET has none. If you add a subroutine GETINSTRUMENT and declare it in the contains section of TYPE INSTRUMENT as you did it for WRITE, CALL pointer % GET(temp) will work. Please make sure that the corresponding dummy arguments of all GET-subroutines have the same name and attributes.

Leave a Comment

Please sign in to add a comment. Not a member? Join today