Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Emulate static self-referential class member in Fortran

Status
Not open for further replies.

Tiwalade

Technical User
Oct 16, 2013
2
ZA
In C++ it is possible to declare a static self-referential class member e.g.

class Employee
{
protected:
int n;
static Employee* empl;
public:
Employee() {}
static void Set(Employee& e);
}

How do I emulate this in Fortran? One way is to declare a global module variable but this is not thread-safe.
Any help is welcomed and appreciated.
 
Which version of Fortran? 90, 95, 03 or 08?
 
I would have declared it as
Code:
class Employee
{
protected:
   int n;
   Employee() {}
public:
   static Employee* Get()
   {
      static Employee empl;
      return &empl;
   }
In Fortran 95, you'd have to have two definitions: the module and the type. Treat the module as a namespace: it isn't really a class. Treat the type as a POD type struct.

The static within the static get method can be done with as a save variable. Just return a pointer to it.
Code:
module EmployeeMod
type EmployeeT
   integer n
end type EmplyeeT

function Get()
   type (EmployeeT), target::empl
   type (EmployeeT), pointer:: Get
   save empl

   Get => empl
end function Get
end module EmployeeMod
This would give you a company with only one employee! haha.
 
You may be able to do it like your original C++ code in F08 but I haven't started exploring classes in Fortran yet. If you want to go down that route, you have to be quite picky about the compiler since not all compilers support the 08 features yet. I know, it came out 6 years ago but Fortran standards don't get implemented as quickly as C/C++ ones.

If the compiler is tied to the hardware (eg XLF on AIX), it could take even longer.
 
Hi xwb,

Thank you for your prompt reply.

I am actually coding in Fortran 2003.
In your Get() function you declare a "empl" variable, is it a module variable or a dummy argument of the function?
 
It is a saved variable i.e. it retains the value on re-entry. Similar concept to static within a function or own variables if you have an Algol 60 background.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top