FB OOP Tutorial

Post your FreeBASIC tips and tricks here. Please don’t post your code without including an explanation.
Imortis
Moderator
Posts: 1719
Joined: Jun 02, 2005 15:10
Location: USA
Contact:

FB OOP Tutorial

Postby Imortis » Jul 16, 2008 12:46

This was originally taken from the FBEdit Forum. I thought someone here might get some use out of it.


Object Oriented Programming (OOP) is the idea that you can treat your custom types like objects. An object has things and does things.
As an example, let’s use a rock. Let’s say we want to simulate a rock. A rock HAS a size and a color. It also DOES things, like rolling and gathering moss. I’m sure that if we really wanted to think about it we could find more things that a rock either HAS or DOES, but for now, we will leave it at that. Here is a small chart:

    ROCK
    • HAS
    • color
    • size
    • DOES
    • roll
    • gather moss


Simple, right? Well, it’s almost that easy in FB. In FB the OOP stuff is used with User Defined Types (UDT), for the moment.

Code: Select all

Type ROCK
   'HAS
   color as uinteger
   size as integer
   'DOES
   Declare Sub roll()
   Declare Sub gatherMoss()
End Type

Sub ROCK.roll()
   'Code here
End Sub

Sub ROCK.gatherMoss()
   'Code here
End Sub


That is the very basics of FB’s OOP. To use the ROCK type, you just DIM a variable of the type ROCK:

Code: Select all

Dim pebble as ROCK

pebble.size = 1 'It’s a small rock
pebble.color = RGB(200,200,200) 'Grey-ish in color

pebble.roll()
pebble.gatherMoss()


See? Neat, huh? Next is the idea of Private and Public. Some things that are attributed to an object may be private, some may be public. Let’s use a person as an example. A person HAS things he may not want to show off to others, but are none the less still part of him (no sick minds, people). For instance, what if you have a big hairy mole on you left butt cheek? You don’t want to show it off to everyone, but it is still a part of you that, for better or for worse, you have to deal with. A person also DOES things that he may not want others to know about. Things that have to be done, but you don’t really want publicized. Like getting a big hairy mole removed from your left butt cheek. These things you would rather keep to yourself. Things which are public are things that you don’t mind other people knowing about. Like your face and reading.
0

Code: Select all

Type PERSON
   Private:
   bigHairyMole as Long 'It’s REALLY big…
   spiderVanes as Single  'As in relationship status…
   
   Declare Sub removeMole(Doctor as String)
   Declare Sub cryInPillow()

   Public:
   face as byte           'because of the teeth
   name as string       'Gotta have one of these
   myCash as single   'Sweet money
   
   Declare Sub read(text as String)
   Declare Sub giveToCharity(money as Single)
End Type

'Put the code for all your subs here


I left out the sub code part this time, because it is exactly the same as last time. Now, the stuff that is public can be used anywhere in your code. The stuff that is private can only be used by things that are a part of the type person. Like this:

Code: Select all

Sub PERSON.giveToCharity(money as Single)
   this.myCash  = this.myCash – money
   this.cryInPillow()
End Sub


See? Giving to charity decreases your cash and makes you cry into a pillow.

Before I go too much further, let me cover a few points of syntax. First, to supply the code for a sub or function that are declared inside a type, you use the type name followed by a dot, then the sub or function name. Also THIS was used in the above examples. This is used to refer to things which are part of the type. This is not strictly required, unless you have two subs, functions, or variables of the same name, one of which is in the type. I use it all the time anyway because it makes code easier to read for me.
Now here is an example of code to use the person type:

Code: Select all

Dim Imortis as PERSON

Imortis.name = “Imortis Inglorian”
Imortis.myCash = 10.00

Imortis.giveToCharity(10.00) 'This works fine
Imortis.removeMole(“Dr. Gupta”) 'This won’t work…  Too public…


See? Easy as pie.

Next up is some of the more advanced OOP topics.

Properties are what I call Getters and Setters. They allow you to get and set values. Now, you may ask, why would you want to do that when you could easily get and set values using “=”? The answer is simple: Presentation. It makes it look better when used in code. Tell me which looks better, this:

Code: Select all

Player.x =1
Player.y =1

Or this:

Code: Select all

Player.coordinates(1,1)


That is what properties are for. Also if you have to do some funky processing on values, properties can make that transparent.

Properties are set up very similar to subs and functions in types:

Code: Select all

Type Player
   _x as integer
   _y as integer
   
   Declare Property X() as integer
   Declare Property X(value as integer)
   
   Declare Property Y() as integer
   Decalre Property Y(value as integer)
End Type

Property Player.X() as integer
   Return this._x
End Property

Property Player.X(value as integer)
   this._x = value
End Property

Property Player.Y() as integer
   Return this._y
End Property

Property Player.Y(value as integer)
   this._y = value
End Property


Now to use them, it’s like this:

Code: Select all

Dim me as Player

me.X = 10
me.Y = 10

Print me.X
Print me.Y


Granted this example is practically useless, but it does show how to use properties. A better way to use it is to calculate values on the fly for things that change too often to want to store it. The wiki shows some far better examples.

Next let’s talk about operator overloading. This is the ability to change the way +, -, *, /, =, and others work for your type.

Let's say you want to add the ages of two people. First we need a person type:

Code: Select all

Type PERSON
   name as String
   age as Ubyte 'Who is going to live over 255 years?
End Type


If you want to add the ages of two people together, you have to do something like this:

Code: Select all

Dim Imortis as PERSON
Dim bigsofty as PERSON

Dim combinedAges as Integer

combinedAges = Imortis.age + bigsofty.age


This works, but is a little sloppy looking. You can do a little better by using operator overloading. For a Type, you can only use certain operators. The assignment operators (+=, -=, *=, /=, \=, Mod=, =, etc.) and the Cast operator. The one we will be using is the cast operator

Code: Select all

Type PERSON
   name as String
   age as Ubyte 'Who is going to live over 255 years?

   Declare Operator Cast() as Integer
End Type

Operator PERSON.Cast() as Integer
   Return Int(this.age)
End Operator


See? Painless. Now to use it, you just do this.

Code: Select all

Dim Imortis as PERSON
Dim bigsofty as PERSON

Dim combinedAges as Integer

combinedAges = Imortis + bigsofty

See? Clear and concise. What happed is when you use the + operator an your two person variables, they are converted to integers, by returning the age variable of the type, then added together and assigned to combinedAges.

Next up is the Constructor. A constructor in a type is a chunk of code that runs as soon as the variable is DIMed. This is useful for many things. A good example of wanting to do this is with videogames. In most games the player starts with 3 to 5 lives.

Code: Select all

Type PLAYER
   lives as Integer
   x as Integer
   y as Integer

   Declare Constructor()
End Type

Constructor PLAYER()
   this.lives = 3
End Constructor

Dim pacMan as PLAYER

Print pacMan.lives


It will already be 3. This has far more complex uses, but this is just a simple example of what you can do. You can also pass arguments to the constructor if you like.

The Destructor is like the Constructor except it happens when you delete a variable or when it goes out of scope. It is particularly useful when you make extensive use of pointers, Allocate, and New. But that is a totally different tutorial. For now, just know that a destructor happens when a variable is removed from scope, or when it is deleted using Delete, or deallocate.

Well, that’s all I got. If you have any questions, just ask and I’ll see If I can clarify.
maddogg6
Posts: 824
Joined: Dec 07, 2005 22:58
Contact:

Postby maddogg6 » Jul 16, 2008 15:41

Excellent tutorial - I think I am getting to understand OOP a little more. Thank you.

edited again: because I am still getting my head around something here...

With the cast operator example....

How does the compiler know that when we call:
combinedAges = Imortis + bigsofty

to add ages and not concatenate the names.

How can we make say another property, like experience - get combined as well in the same operation.

teamA = imortis + bigsofty

which would result in combined age *and* experience.

In other words - I am having trouble understanding how the compiler knew to add the age, and not concatenate the names.
I am thinking it has to do with the fact the ages were casted to integer and matches the type of the result 'combinedAges; - but what if we use integers for experience as well?

*hopes that made sense*

thanks for the tutrial in any case. /edit
Last edited by maddogg6 on Jul 16, 2008 15:49, edited 2 times in total.
Imortis
Moderator
Posts: 1719
Joined: Jun 02, 2005 15:10
Location: USA
Contact:

Postby Imortis » Jul 16, 2008 15:45

If you have any other questions, be sure to ask.
I want to make this a growing tutorial. If any new info is required, I'll add it on to the end.

That way before long we will have a completely comprehensive tutorial for Object Oriented Programming.

{plug} Only you people of the forum can help me in my quest. If you folks out there don't help out, who will?{/plug}
D.J.Peters
Posts: 8024
Joined: May 28, 2005 3:28
Contact:

Postby D.J.Peters » Jul 16, 2008 17:47

From the FreeBASIC Wiki written by YetiFoot.

Beginners Guide to Types as Objects
Part I
Part II

this infos can be helpful too

nice to see tutorials like yours

Joshy
Imortis
Moderator
Posts: 1719
Joined: Jun 02, 2005 15:10
Location: USA
Contact:

Postby Imortis » Jul 16, 2008 17:52

Those tutorials were actually how I learned how to use the OOP features in FB. However, for many people, they did not quite do the job. I posted this tutorial on the FBEdit Forum because someone was looking for an "easy" tutorial on the OOP features. So I wrote one worded and presented in a simple manner so that, hopefully, people who could not understand the more technical links you posted above would be able to grasp the ideas and concepts.
DaveUnit
Posts: 239
Joined: Apr 20, 2006 15:47
Location: Central MA
Contact:

Postby DaveUnit » Jul 17, 2008 0:24

Nice tutorial. Beginners can learn complex topics like OOP if there are tutorials such as these that explain everything in basic terms and relate to basic things they already know about.
Imortis
Moderator
Posts: 1719
Joined: Jun 02, 2005 15:10
Location: USA
Contact:

Postby Imortis » Jul 17, 2008 0:32

Thanks DaveUnit. As I said before, any ideas on what to add are a big help. Also, if there are any other topics that need a similar explanation, then please let me know.

I am currently trying to learn threading so I can do a similar tutorial on it.
DaveUnit
Posts: 239
Joined: Apr 20, 2006 15:47
Location: Central MA
Contact:

Postby DaveUnit » Jul 17, 2008 1:22

I made a matrices class once that is a great example of OOP. A more simple one to demonstrate operator overloading would be a Fraction class with overloaded operators for +,-,*,/, casts to strings, singles, and doubles, etc. I'll make that class if you would be interested in using it in another tutorial.
Imortis
Moderator
Posts: 1719
Joined: Jun 02, 2005 15:10
Location: USA
Contact:

Postby Imortis » Jul 17, 2008 1:46

*thinks* Sounds good. It would be a good bridge from the code I have to a really useful example. Thank you very much.

This is the kind of thing I was trying to encourage with this idea.
JohnK
Posts: 279
Joined: Sep 01, 2005 5:20
Location: Earth, usually
Contact:

Postby JohnK » Jul 17, 2008 5:34

FB OOP is really moving along. Nice tutorial.

I don't know if it helps others but I learned the concept of OOP by thinking "its a Quick Basic TYPE variable with SUBs and FUNCTIONS, and DIM variables, and CONST all packed inside." When I thought about it, it was a nice way to make a MODULE all inside a TYPE variable, then I could have many different variables, all using the same code in the MODULE but being all separate.

Will there be EVENTS in future versions of FB? Kind of like the old ON KEY() GOSUB
Imortis
Moderator
Posts: 1719
Joined: Jun 02, 2005 15:10
Location: USA
Contact:

Postby Imortis » Jul 17, 2008 12:17

I believe some one sent me an email about this, but I got trigger happy with the empty spam folder button. I saw it just before it disappeared. So if you could send it again, I would appreciate it.
DaveUnit
Posts: 239
Joined: Apr 20, 2006 15:47
Location: Central MA
Contact:

Postby DaveUnit » Jul 17, 2008 15:05

Well FBEdit is having some serious issues on my pc. So here's a protoype of a fraction class for now.

Code: Select all

type Fraction
   private:
      '' Numerator and denomenator
      as integer num_, denom_
      
   public:
      '' Constructors
      declare constructor()
      declare constructor(newNum as integer, newDenom as integer)
      '' Returns the fraction in string form. example: 1/4
      declare operator cast() as string
               '' Reduces fraction
      declare sub reduce()
      '' Properties
      declare property num() as integer
                declare property num(newNum as integer)
      declare property denom() as integer
                declare property denom(newDenom as integer)
end type

'' Operators to perform typical math functions on Fractions
declare operator +(byref rhs as Fraction, byref lhs as Fraction) as Fraction
declare operator -(byref rhs as Fraction, byref lhs as Fraction) as Fraction
declare operator *(byref rhs as Fraction, byref lhs as Fraction) as Fraction
declare operator /(byref rhs as Fraction, byref lhs as Fraction) as Fraction
MystikShadows
Posts: 606
Joined: Jun 15, 2005 13:22
Location: Upstate NY
Contact:

Postby MystikShadows » Jul 17, 2008 15:57

That tutorial was pretty good Immortis, It makes me raise a question.

I understand that inheritance isn't done yet. However, am I correct to assume that any property defined in an object could be of any other defined object types? for example:

Code: Select all

TYPE Person
     .....Object properties
     .....Object Methods
END TYPE

TYPE Character
        PersonData AS Person
        RoleData   ....
END TYPE


Should be valid today? If so, perhaps an example of that could be added.
Imortis
Moderator
Posts: 1719
Joined: Jun 02, 2005 15:10
Location: USA
Contact:

Postby Imortis » Jul 17, 2008 16:47

@Mystic:
Yes that is available.

The only issue is that any type must have at least one variable inside it. You can't have one with nothing but subs, properties, operators, and the like.

I'll see what I can do.
egocks
Posts: 20
Joined: Mar 27, 2008 2:02
Location: Philippines

Re: FB OOP Tutorial

Postby egocks » Jul 21, 2008 7:57

Imortis wrote:what if you have a big hairy mole on you left butt cheek?

this is the only concept that I can't comprehend in this tutorial. :P

other than that, this tutorial is great. it has answered all my questions about OOP in FB very clearly.

with regards to OOP in FB, it would be nice to have inheritance and abstraction in the future, because that's where the real fun begins.

Return to “Tips and Tricks”

Who is online

Users browsing this forum: No registered users and 2 guests