Here is some sample code I thought would be helpful to people wanting to get started with some OOP style coding. It uses a minimum of INSTANCE variables including a dynamic string to demonstrate saving objects to a file and later retrieving them. Each object defined from the cRecord class is a data base record listing a name and age of a person. These records are stored in a global array of objects.
Code:
GLOBAL oRecord() AS iRecord GLOBAL numRecords AS LONG CLASS cRecord INSTANCE sName AS STRING INSTANCE age AS LONG INTERFACE iRecord: INHERIT IUNKNOWN PROPERTY GET sName AS STRING PROPERTY = sName END PROPERTY PROPERTY GET age AS LONG PROPERTY = age END PROPERTY METHOD addRecord(s AS STRING, n AS LONG) sName = s: age = n END METHOD METHOD saveRecord(fileNo AS LONG) LOCAL n AS LONG n = LEN(sName): PUT fileNo,, n: PUT fileNo,, sName PUT fileNo,, age END METHOD METHOD openRecord(fileNo AS LONG) LOCAL n AS LONG GET fileNo,, n: sName = SPACE$(n): GET fileNo,, sName GET fileNo,, age END METHOD END INTERFACE END CLASS FUNCTION PBMAIN LOCAL i AS LONG, fileName AS STRING DIM oRecord(3) AS iRecord LET oRecord(1) = CLASS "cRecord" LET oRecord(2) = CLASS "cRecord" LET oRecord(3) = CLASS "cRecord" fileName = "Sample File with Objects" IF ISFILE(fileName) THEN 'open file and list records fileOpen(fileName) FOR i = 1 TO 3 MSGBOX "Name: " + oRecord(i).sName + $CRLF + "Age: " + STR$(oRecord(i).age) NEXT i ELSE 'save records oRecord(1).addRecord("Mary Ann Rutherford", 25) oRecord(2).addRecord("Robert A. Jones", 36) oRecord(3).addRecord("Sam Smith", 29) numRecords = 3 fileSave(fileName) MSGBOX "Done saving... run again to open file and list records" END IF END FUNCTION SUB fileSave(fileName AS STRING) LOCAL i, fileNo AS LONG fileNo = FREEFILE OPEN fileName FOR BINARY AS fileNo PUT fileNo,, numRecords FOR i = 1 TO numRecords oRecord(i).saveRecord(fileNo) NEXT i CLOSE fileNo END SUB SUB fileOpen(fileName AS STRING) LOCAL i, fileNo AS LONG fileNo = FREEFILE OPEN fileName FOR BINARY AS fileNo GET fileNo,, numRecords FOR i = 1 TO numRecords oRecord(i).openRecord(fileNo) NEXT i CLOSE fileNo END SUB
Comment