Constructors in FreeBASIC

FreeBASIC continues to impress me with its modernity. I already found out that it’s possible to implement C-style pointers in FreeBASIC — and it turns out that you can have C++ – style constructor functionality, as well (code that runs automatically when an object is instantiated.)

For our “object,” we’ll use a custom FreeBASIC type :

type node
    x as double
    y as double
    visited as ubyte
    end type

It would be nice if we could assign default properties to these values automatically when they are allocated. Looking through the documentation, it seems provision is made for this:

type node
    x as double = 0
    y as double = 0
    visited as ubyte = 0
    end type

This works, of course. But what if we wanted random values — would that work?

type node
    x as double = rnd*100
    y as double = rnd*100
    visited as ubyte = 0
    end type

It turns out that this works, even when allocating an entire array of the type:

dim as node lotsOfNodes(1000)  'This will allocate the memory AND assign default values!

There was only one question, at this point. How far could we go? Was it possible to call a function and therefore run arbitrary code? Yes!

'Demonstration of "constructor"-type initialization

'Copyleft 2022, M. Eric Carr / Paleotechnologist.Net
'(CC:BY-NC-SA)

const MAXNODES = 20

declare function myFunction(x as double) as double

type node
   x as double = myFunction(100)
   y as double = myFunction(100)
   visited as integer = 0
   end type
   
dim as node f(MAXNODES) 'Nodes are initialized as they are created
dim as integer n

for n=0 to MAXNODES-1
   print f(n).x,f(n).y,f(n).visited 'View the contents to check initialization
   next n

sleep

function myFunction(x as double) as double
   static callCount as ulongint 
   callCount=callCount+1
   return rnd*x
   end function
   

Maybe they’re still not true “objects” — but they pass the duck test (with the possible exception of not having similar destructor functionality.) At any rate, it’s fun to see a language that’s ultimately still a descendant of 1964 Dartmouth BASIC capable of things like running arbitrary code implicitly on object creation.

…I wonder if it’s thread-safe?

This entry was posted in BASIC, Coding. Bookmark the permalink.

Leave a Reply