Skip to content
Object-Oriented FreeBASIC
step 1/5

Reading — step 1 of 5

Learn

~2 min readOOP, Pointers, File I/O

FreeBASIC adds OO features that older BASIC dialects lacked. Inheritance, virtual methods, constructors.

Type with methods

TYPE Counter
    count AS INTEGER
    DECLARE Sub Increment()
    DECLARE Function Get() AS INTEGER
END TYPE

Sub Counter.Increment()
    this.count += 1
End Sub

Function Counter.Get() AS INTEGER
    Return this.count
End Function

DIM c AS Counter
c.count = 0
c.Increment()
c.Increment()
PRINT c.Get()       ' 2

this is the implicit instance reference inside methods. Methods are declared inside the TYPE and defined outside.

Constructors and destructors

TYPE Person
    name AS STRING
    age AS INTEGER
    DECLARE CONSTRUCTOR(n AS STRING, a AS INTEGER)
    DECLARE DESTRUCTOR()
END TYPE

CONSTRUCTOR Person(n AS STRING, a AS INTEGER)
    this.name = n
    this.age = a
End CONSTRUCTOR

DESTRUCTOR Person()
    PRINT "goodbye "; this.name
End DESTRUCTOR

DIM ada AS Person = Person("Ada", 36)
PRINT ada.name; ada.age

Inheritance with EXTENDS

TYPE Animal EXTENDS Object
    name AS STRING
    DECLARE CONSTRUCTOR(n AS STRING)
    DECLARE VIRTUAL Function Sound() AS STRING
END TYPE

CONSTRUCTOR Animal(n AS STRING)
    this.name = n
End CONSTRUCTOR

Function Animal.Sound() AS STRING
    Return "..."
End Function

TYPE Dog EXTENDS Animal
    DECLARE CONSTRUCTOR(n AS STRING)
    DECLARE Function Sound() AS STRING OVERRIDE
END TYPE

CONSTRUCTOR Dog(n AS STRING)
    Base(n)
End CONSTRUCTOR

Function Dog.Sound() AS STRING
    Return "woof"
End Function

VIRTUAL makes a method overridable; OVERRIDE declares the override. Base(...) calls the parent constructor.

Object inheritance

All types extending Object (FreeBASIC's root) participate in dynamic dispatch:

DIM a AS Animal PTR
a = NEW Dog("Rex")
PRINT a->Sound()      ' "woof" — virtual dispatch
DELETE a

Pointer dereference uses ->. NEW allocates, DELETE frees.

Visibility

TYPE Vault
PRIVATE:
    secret AS STRING
PUBLIC:
    DECLARE Sub SetSecret(s AS STRING)
    DECLARE Function GetSecret() AS STRING
END TYPE

Looks like C++. Inside the type, PRIVATE: and PUBLIC: (and PROTECTED:) gate access to following members.

Operator overloading

FreeBASIC supports operator overloading for types — uncommon to need but available:

OPERATOR + (a AS Vector, b AS Vector) AS Vector
    DIM r AS Vector
    r.x = a.x + b.x
    r.y = a.y + b.y
    Return r
End OPERATOR

This FB OO syntax is closer to C++ than to VB.NET. Not the BASIC you knew from the 80s.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…