This is the mail archive of the fortran@gcc.gnu.org mailing list for the GNU Fortran project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Constructors for dynamically allocated CLASS data


Quick question about constructors in Fortran 2003/08. Say I have an abstract base class such as Shape, with child classes such as Circle, Square, etc. In C++, you can dynamically allocate these data using something like:
Shape *s;
s = new Circle(3);  // Construct a circle with radius=3

I'm wondering if there is a corresponding idiom in Fortran 2003. I can write procedures that accept CLASS(Circle) or CLASS(Square) and act as constructors, but it appears that you can't pass a dynamically allocated instance of CLASS(Shape) into these procedures. In other words:
CLASS(Shape), ALLOCATABLE :: s
ALLOCATE(Circle::s)
CALL Circle_ctor(s,3) // Not allowed

The only other approach I can think of is to write the constructor procedures such that they accept CLASS(Shape), and then use SELECT TYPE to access the child data. This is not very elegant though, and gets cumbersome if I want to use separate procedures for each child constructor (and then now you need to do error checking in each constructor procedure to make sure that the dynamic type actually is what was expected).

Surely there is a better way to do this?

Thanks in advance,
John


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]