PDA

View Full Version : MyClass & MyClassCOM - simple demo of creating module class



Petr Schreiber
20-05-2013, 20:29
Thanks to fact Eros is dark magician, ThinBASIC modules can define not just equates, variables, UDTs and functions... they can define classes too. And what is the best about it? You can define classes even from languages which have no OOP support.

The attached file contains:

source code for thinBasic_MyClass module - it shows how to define class using custom memory allocations (universal, possible from any language)
source code for thinBasic_MyClassCOM - it shows how to define class by wrapping COM object (preferred way if you are PowerBASIC programmer)
example scripts which use MyClass and MyClassCOM sample classes


To make it simple and the most illustrative, the MyClass module is kept very simple:

it has constructor, which can optionally take one parameter
class internally stores one number, which you can read or write using get/set method
that is all


Of course, more powerful classes can be done, but to introduce you softly to module developement of classes, this is the way to keep it easy to understand.

Here is test code of the classes - you can see using objects in ThinBASIC is intuitive and nothing to be afraid of!


Uses "MyClass", "Console"

Dim a As MyClass
Dim b As MyClass

Print "Instantiating object a..."
a = New MyClass ' -- No parameter specified, MyClass will hold default -1 (defined in module)
PrintL "DONE"

Print "Instantiating object b..."
b = New MyClass(789) ' -- Some values can be passed to constructor, it is up to the author of class if this is allowed or not
PrintL "DONE"

PrintL "Default value inside a:", a.Get()
PrintL "Default value inside b:", b.Get()

PrintL "Setting new values for a and b..."

a.Set(123)
b.Set(456)

PrintL "Value inside a now:", a.Get()
PrintL "Value inside b now:", b.Get()

PrintL
PrintL "Press any key to quit..."
WaitKey


I hope you will like it. There is more to class developement, but more about it in future.


Petr

ReneMiner
20-05-2013, 20:51
So I can not "Free" or "Kill" some class already?
And does it need to specify the Index of class when creating a New one or is this optional or is this no Index but some flag inside parens?

Just for fun and better readability I re-arranged the thincore.inc a little bit. Why do we have those nice commenting-functions in thinAir?

Petr Schreiber
20-05-2013, 23:05
Hi Rene,

it is not index of class, it is parameter of constructor. Imagine Vector class - it could take as parameter the X, Y, Z coordinates...
It is up to programmer whether the constructor has parameters or not.

Object variables are killed once the run out of scope... You could add Free method if you want to do that earlier.


Petr

D.J.Peters
21-05-2013, 00:09
Looks easy,
thank you for the tiny examples.

Joshy