OOP easy with Macro New and Delete
Posted: Wed Jul 18, 2007 10:46 am
The Macro:
Test:
Code: Select all
; File New_Delete.pb
Macro New(Pointer,Class)
Pointer#_.Class#_=AllocateMemory(SizeOf(Class#_))
Pointer#_\Vtable=?Class
Pointer#.Class=@Pointer#_\Vtable
Class(Pointer)
EndMacro
Macro Delete(Pointer,Class)
Pointer#_.Class#_=Pointer
Class#_(Pointer)
FreeMemory(Pointer)
EndMacro
Test:
Code: Select all
; Important:so that the macro works, it's imperative
; - that the name of the structure is the same that the name of the interface followed by the character "_"
; - that the structure possesses the variable Vtable (First position in structure; Important)
; - that the names of procedures Constructor and Destructor possess the same name as that of the interface
; - that the name of load of the data in DataSection is the same as that of the interface
; For Reminder: *This = Address of the variable Vtable
; it is important that this variable Vtable is declared in the first position
; in the Structure so that: *This.Calcul _ =*This.Calcul
; if Vtable was declared in the second position, we would have: *This.Calcul_ =*This.Calcul-8
; it thus allows us to replace in the procedures *This.Calcul by *This.Calcul_
; we so choose to work on the functions or on the members by taking the one or the other one
; Functions of the class
Interface Calcul
SetData(a.l,b.l)
Addition()
Multiplication()
EndInterface
; Member of the class
Structure Calcul_
Vtable.l ; Important first position
a.l
b.l
EndStructure
; Constructor of the class
; Called after creation of the resources
Procedure Calcul(*This.Calcul_)
Debug "--------------------------"
Debug "Constructor"
*This\a=0
*This\b=0
Debug "--------------------------"
EndProcedure
; Destructor of the class
; Called before liberation of the resources
Procedure Calcul_(*This.Calcul_)
Debug "--------------------------"
Debug "Destructor"
Debug "--------------------------"
EndProcedure
IncludeFile "New_Delete.pb"
Procedure.l Setdata(*This.Calcul_,a.l,b.l)
*This\a=a
*This\b=b
EndProcedure
Procedure.l Addition(*This.Calcul_)
ProcedureReturn *This\a + *This\b
EndProcedure
Procedure.l Multiplication(*This.Calcul_)
ProcedureReturn *This\a * *This\b
EndProcedure
New(*Pointeur,Calcul)
*Pointeur\Setdata(5,3)
Debug "Addition= "+Str(*Pointeur\ Addition())
Debug "Multiplication= "+Str(*Pointeur\ Multiplication())
Delete(*Pointeur,Calcul)
DataSection
Calcul:
Data.l @SetData(),@Addition(),@Multiplication()
EndDataSection