Classes

A class declares an object's fields and its methods together. Classes are an x addition: PureBasic has no classes. PureBasic programmers make objects by hand, from an Interface, a structure whose first field points to a table of procedure addresses, and a DataSection holding that table, all kept in step by hand. x builds exactly that from a class. So an object of a class can be used wherever a PureBasic interface is expected, and hand-made objects keep working.

Classes can be written PureBasic style or C style (see C style), and the two can be mixed in one program.

Declaring a class ✅

Class Name [Extends Base | Implements Interface]
  field.type ...
  Procedure[.type] Method([parameters])
    ...
  EndProcedure
  ...
EndClass

Fields are written as in a Structure. Methods are procedures written inside the class. New Name(arguments) makes an object, and FreeObject(object) frees it.

OpenConsole()
Class Counter
  label$
  count.i
  Procedure New(label$)
    this\label$ = label$
  EndProcedure
  Procedure Bump(n = 1)
    count + n
  EndProcedure
  Procedure.s Show()
    ProcedureReturn label$ + ": " + Str(count)
  EndProcedure
EndClass

c.Counter = New Counter("clicks")
c\Bump() : c\Bump(5)
PrintN(c\Show())
PrintN(Str(c\count))
FreeObject(c)

Output:

clicks: 6
6
  • A variable of a class type (c.Counter) holds the object's address: objects are always references. d.Counter = c gives a second name for the same object, not a copy.
  • obj\Method(...) calls a method and obj\field reads or writes a field, as with an interface and a structure.
  • *obj.Counter (and C style Counter *obj) means the same as obj.Counter, as PureBasic allows for an interface.
  • A class must be declared before it is used, like a structure, and not inside a procedure. It can be in a module (see Classes in modules). Its methods can be written after it (see Methods written after the class).
  • A class can't take a name that is a type letter (A, B, C, W, U, L, I, Q, F, D, S): c.D would be ambiguous.
  • Member names are not case sensitive, so a field and a method can't share a name (total and Total()).

Inside a method ✅

Inside a method, this is the object the method was called on. this is the same as *this, which is how a hand-written PureBasic method names it.

  • A field can be used by its name alone (count + n), or as this\count.
  • A parameter or local variable of the same name comes first. In New(label$) above, label$ is the parameter, so the field is written this\label$.
  • A field comes before a global of the same name.
  • Another method of the class can be called by its name alone (Show()), or as this\Show(). Either way it is called through the object, so a subclass's version is the one that runs.
  • Collection fields work the same way: AddElement(items()), ForEach items(), ReDim grid(n).

Constructors and destructors ✅

The method named New is the constructor and Destroy is the destructor.

  • New Class(arguments) allocates the object (fields start at 0 and "", collection fields empty), then calls New with the arguments. A class without New takes no arguments.
  • A constructor returns its object by itself: ProcedureReturn inside it takes no value.
  • FreeObject(object) calls Destroy, then the base class's Destroy, and so on up the chain. Then it frees the object's strings, lists, maps and arrays, and the object itself.
  • FreeObject(0) does nothing. An address that New didn't make is left alone, as far as x can tell. Freeing an object twice is an error x does not detect, as with FreeMemory.
  • C style delete object is the same as FreeObject(object).
OpenConsole()
Class Tree
  name$
  left.Tree
  right.Tree
  Procedure New(name$)
    this\name$ = name$
  EndProcedure
  Procedure Destroy()
    PrintN("free " + name$)
    FreeObject(left)
    FreeObject(right)
  EndProcedure
EndClass

t.Tree = New Tree("root")
t\left = New Tree("L")
t\right = New Tree("R")
t\left\left = New Tree("LL")
FreeObject(t)

Output:

free root
free L
free LL
free R

A field can hold an object of its own class (left.Tree), and an empty one is 0.

Inheritance ✅

Extends Base makes a class with everything the base class has, plus its own fields and methods.

  • A method with the same name as one of the base's replaces it, and must have the same return type and parameters. A call through any reference, even one typed as the base class, runs the replacement.
  • Super\Method(arguments) calls the base class's version.
  • A class without its own New uses the nearest base class's New. A class with its own New calls the base's only if it says so: Super\New(...).
  • Destructors run automatically, the class's own first, then each base's.
OpenConsole()
Class Animal
  name$
  legs.i
  Procedure New(name$, legs = 4)
    this\name$ = name$
    this\legs = legs
  EndProcedure
  Procedure.s Describe()
    ProcedureReturn name$ + " has " + Str(legs) + " legs"
  EndProcedure
  Procedure Destroy()
    PrintN("bye " + name$)
  EndProcedure
EndClass

Class Dog Extends Animal
  tricks.i
  Procedure.s Describe()
    ProcedureReturn Super\Describe() + " and knows " + Str(tricks) + " tricks"
  EndProcedure
  Procedure Learn()
    tricks + 1
  EndProcedure
  Procedure Destroy()
    PrintN("dog gone")
  EndProcedure
EndClass

Procedure Show(a.Animal)
  PrintN(a\Describe())
EndProcedure

a.Animal = New Animal("Tweety", 2)
d.Dog = New Dog("Rex")
d\Learn() : d\Learn()
Show(a)
Show(d)
FreeObject(a)
FreeObject(d)

Output:

Tweety has 2 legs
Rex has 4 legs and knows 2 tricks
bye Tweety
dog gone
bye Rex

Private and Protected ✅

Put Private or Protected in front of a field or a method:

Who can use it
(neither) anyone
Protected the class's methods, and those of classes that extend it
Private the class's own methods only

A Private method is called directly rather than through the method table, so a subclass can't replace it.

OpenConsole()
Class Account
  owner$
  Protected balance.i
  Private pin.i
  Procedure New(owner$, pin)
    this\owner$ = owner$
    this\pin = pin
  EndProcedure
  Procedure Deposit(amount)
    balance + amount
  EndProcedure
  Private Procedure.i PinOK(tried)
    ProcedureReturn Bool(tried = pin)
  EndProcedure
  Procedure.i Withdraw(amount, tried)
    If PinOK(tried) And amount <= balance
      balance - amount
      ProcedureReturn #True
    EndIf
    ProcedureReturn #False
  EndProcedure
EndClass

Class Savings Extends Account
  Procedure.i Interest()
    ProcedureReturn balance / 100     ; Protected: allowed here
  EndProcedure
EndClass

s.Savings = New Savings("Ann", 1234)
s\Deposit(500)
PrintN(Str(s\Withdraw(100, 1111)) + " " + Str(s\Withdraw(100, 1234)) + " " + Str(s\Interest()))

Output:

0 1 4

Outside the class, s\balance, s\pin and s\PinOK(1) are errors ("'balance' is Protected in class 'Account'").

Collection fields ✅

A class can have List, Map and Array fields, written as in a structure. They are made with the object and freed with it.

OpenConsole()
Class Bag
  List items.s()
  Map counts.i()
  Procedure Add(s$)
    AddElement(items()) : items() = s$
    counts(s$) + 1
  EndProcedure
  Procedure.s Dump()
    Protected r$
    ForEach items()
      r$ + items() + "=" + Str(counts(items())) + " "
    Next
    ProcedureReturn r$
  EndProcedure
EndClass

b.Bag = New Bag
b\Add("apple") : b\Add("fig") : b\Add("apple")
PrintN(b\Dump())
PrintN(Str(ListSize(b\items())) + " " + Str(MapSize(b\counts())))
FreeObject(b)

Output:

apple=2 fig=1 apple=2 
3 2

Implements ✅

Implements Interface makes a class whose objects are that interface's objects. The class must have every method of the interface, with the same return type and parameters, and can have more. An object can then be used through a variable of the interface's type.

Class Name [Extends Base] Implements Interface [, Interface ...]
OpenConsole()
Interface Shape
  Area.d()
  Name.s()
EndInterface

Class Square Implements Shape
  side.d
  Procedure New(side.d)
    this\side = side
  EndProcedure
  Procedure.s Name()
    ProcedureReturn "square"
  EndProcedure
  Procedure.d Area()
    ProcedureReturn side * side
  EndProcedure
EndClass

s.Shape = New Square(3)
PrintN(s\Name() + " " + StrD(s\Area()))

Output:

square 9

A class that extends one that implements an interface implements it too.

A class can extend a class and implement interfaces, and implement several. Its methods can come from the class itself or from its bases, and a subclass's replacement is the one called through every interface.

OpenConsole()
Interface Speaker
  Speak.s()
EndInterface
Interface Walker
  Walk.s(steps.i)
EndInterface

Class Animal
  name$
  Procedure New(name$) : this\name$ = name$ : EndProcedure
EndClass

Class Dog Extends Animal Implements Speaker, Walker
  Procedure.s Speak() : ProcedureReturn name$ + " says woof" : EndProcedure
  Procedure.s Walk(steps.i) : ProcedureReturn name$ + " walks " + Str(steps) : EndProcedure
EndClass

Class Puppy Extends Dog
  Procedure.s Speak() : ProcedureReturn name$ + " says yip" : EndProcedure
EndClass

Procedure Talk(s.Speaker)
  PrintN(s\Speak())
EndProcedure

d.Dog = New Dog("Rex")
p.Puppy = New Puppy("Bit")
Talk(d)
Talk(p)
w.Walker = p
PrintN(w\Walk(3))

Output:

Rex says woof
Bit says yip
Bit walks 3

How it works: an object has one method table, which can only follow one interface's order. That is the first class's, or its first interface's when it has no base class. Each other interface gets a small view inside the object: the address of a table in that interface's order, and the object's address. An object stored in (or passed as) such an interface becomes the address of its view, and the view's table calls the object's methods. So:

  • Calling through the interface works as usual, and an object of 0 stays 0.
  • The interface variable holds a different address from the object's. Compare objects through their class variables, and free them with those too: FreeObject leaves a view alone.

Properties ✅

A property looks like a field to the code using it, but reading it runs its Get and storing into it runs its Set. It can check what it is given, work its value out from other fields, or be read-only.

Property[.type] Name
  Get
    ...                  ; ProcedureReturn the value
  Set[(parameter)]
    ...                  ; the new value: the parameter, or value (value$ for a string)
EndProperty
  • Either Get or Set can be left out: a property without Set can only be read, and one without Get only set.
  • obj\Age + 1, obj\Age += 1 and obj\Age++ run Get, then Set. Inside the class's methods a property can be used by its name alone, like a field.
  • Private and Protected work as for methods. A subclass can replace a property of its base, and the replacement is used through every reference, as for methods.
  • Inside a property, a line can't start with a name Get or Set (those begin its parts).
  • A property can be Static: see Static fields and methods.
  • C style: int Age { get { return years } set { years = value } }, with set(int v) { } to name the parameter.
OpenConsole()
Class Person
  Private years.i
  Property.i Age
    Get
      ProcedureReturn years
    Set
      If value < 0 : value = 0 : EndIf
      years = value
  EndProperty
  Property.i Decades
    Get : ProcedureReturn Age / 10
  EndProperty
EndClass

class Temperature {
  double celsius
  double Fahrenheit {
    get { return celsius * 9 / 5 + 32 }
    set { celsius = (value - 32) * 5 / 9 }
  }
}

p.Person = New Person
p\Age = 41
p\Age + 2
p\Age++
PrintN(Str(p\Age) + " " + Str(p\Decades))
p\Age = -5
PrintN(Str(p\Age))
Temperature *t = new Temperature()
t->Fahrenheit = 212
PrintN(StrD(t->celsius))

Output:

44 4
0
100

Classes in modules ✅

A class can be declared in a module:

  • in DeclareModule, it is public: outside the module it is Module::Class (New Zoo::Animal("Rex"), a.Zoo::Animal), or Class after UseModule;
  • in Module, it is the module's own, and outside it is an error.

Inside the module, its classes are used by their names alone, as are their Static members (Animal::count) and the methods written after them (Procedure.s Animal::Describe(), in the Module). A class can extend another module's public class (Extends Zoo::Animal) and implement another module's interfaces. Different modules (and the program) can each have a class of the same name.

OpenConsole()
DeclareModule Zoo
  Class Animal
    name$
    Static count.i
    Procedure New(name$) : this\name$ = name$ : count + 1 : EndProcedure
    Declare.s Describe()
  EndClass
EndDeclareModule

Module Zoo
  Procedure.s Animal::Describe()
    ProcedureReturn name$ + " (" + Str(Animal::count) + " so far)"
  EndProcedure
EndModule

a.Zoo::Animal = New Zoo::Animal("Rex")
PrintN(a\Describe())
UseModule Zoo
b.Animal = New Animal("Bit")
PrintN(b\Describe() + " " + Str(Animal::count))

Output:

Rex (1 so far)
Bit (2 so far) 2

Outside the module, a class's Static members are written Module::Class::name (Zoo::Animal::count, Zoo::Animal::Census()), or Class::name after UseModule.

Objects anywhere ✅

An object can be kept in a variable, a structure field, an array, a list or a map, and called through any of them. f()\Method() and a(i)\Method() evaluate f() or i once.

OpenConsole()
Class Pet
  name$
  Procedure New(name$)
    this\name$ = name$
  EndProcedure
  Procedure.s Speak()
    ProcedureReturn name$ + "!"
  EndProcedure
EndClass

NewList pets.Pet()
AddElement(pets()) : pets() = New Pet("Rex")
AddElement(pets()) : pets() = New Pet("Tom")
ForEach pets()
  Print(pets()\Speak() + " ")
Next
PrintN("")
ForEach pets()
  FreeObject(pets())
Next

Output:

Rex! Tom! 

Static fields and methods ✅

Static in front of a field or a method makes it the class's, not each object's: there is one of it, however many objects there are (none included).

  • Outside the class it is written Class::name: Dog::count, Dog::HowMany(). Inside the class's methods, its name alone is enough.
  • A Static field can have a starting value (Static count.i = 10) and can be a list, a map or an array (Static NewList all.s()). It is a global variable, so it is shared by every thread.
  • A Static method has no object: no this, and no fields or methods of an object. It isn't in the method table, so a subclass can't replace it.
  • A subclass shares its base's Static members: Puppy::count is Dog::count.
  • Private and Protected work as for other members, before or after Static.
  • A property can be Static too: Static Property.i Volume … EndProperty (C style static int Volume { get { } set { } }). It is used as Class::Volume, or Volume inside the class, and its Get and Set are Static methods.
OpenConsole()
Class Settings
  Private Static vol.i
  Static Property.i Volume
    Get : ProcedureReturn vol
    Set
      If value > 11 : value = 11 : EndIf
      vol = value
  EndProperty
  Static Procedure Reset()
    Volume = 0
  EndProcedure
EndClass

Settings::Volume = 5
Settings::Volume + 2
PrintN(Str(Settings::Volume))
Settings::Volume = 99
PrintN(Str(Settings::Volume))
Settings::Reset()
PrintN(Str(Settings::Volume))

Output:

7
11
0
OpenConsole()
Class Dog
  name$
  Static count.i
  Static NewList names.s()
  Procedure New(name$)
    this\name$ = name$
    count + 1
    AddElement(names()) : names() = name$
  EndProcedure
  Static Procedure.s Everyone()
    Protected r$
    ForEach names() : r$ + names() + " " : Next
    ProcedureReturn r$ + "(" + Str(count) + ")"
  EndProcedure
EndClass

PrintN(Dog::Everyone())
a.Dog = New Dog("Rex")
b.Dog = New Dog("Bit")
PrintN(Dog::Everyone())
Dog::count = 0
PrintN(Str(Dog::count) + " " + Str(ListSize(Dog::names())))

Output:

(0)
Rex Bit (2)
0 2

Methods written after the class ✅

A method can be declared in the class and written after it, as Class::Method. This keeps a long class readable, with its fields and the list of what it can do in one place.

  • In the class: Declare[.type] Method(parameters), as for a procedure. Static Declare for a Static method.
  • After the class: Procedure[.type] Class::Method(parameters) … EndProcedure, with the same return type and parameters. Inside, everything is as for a method written in the class (this, fields by name, Super).
  • Constructors and destructors too: Declare New(name$), then Procedure Dog::New(name$).
  • Every method declared must be written, once, in the same program.
OpenConsole()
Class Shape
  name$
  Declare New(name$)
  Declare.d Area()
  Declare.s Describe()
EndClass

Class Square Extends Shape
  side.d
  Declare.d Area()
EndClass

Procedure Shape::New(name$)
  this\name$ = name$
EndProcedure

Procedure.d Shape::Area()
  ProcedureReturn 0
EndProcedure

Procedure.s Shape::Describe()
  ProcedureReturn name$ + " of area " + StrD(Area())
EndProcedure

Procedure.d Square::Area()
  ProcedureReturn side * side
EndProcedure

s.Square = New Square("square")
s\side = 3
PrintN(s\Describe())

Output:

square of area 9

C style ✅

A class can also be written in C style, with braces. Its members are written as C-style declarations and functions:

C style PureBasic style
class Dog : Animal { } or class Dog extends Animal { } Class Dog Extends Animal … EndClass
class Sq implements Shape { } Class Sq Implements Shape
string name / int legs name$ / legs.i
int Square(int n) { return n * n } Procedure.i Square(n) … EndProcedure
Dog(string name) { } (the class's name) Procedure New(name$)
~Dog() { } Procedure Destroy()
private: protected: public: (for what follows) Private / Protected in front of each member
this->x, super->Describe() this\x, Super\Describe()
static int count, static int Count() { } Static count.i, Static Procedure.i Count()
string Describe() (no body) in the class, then string Dog::Describe() { } Declare.s Describe(), then Procedure.s Dog::Describe()
new Dog("Rex"), delete d New Dog("Rex"), FreeObject(d)
OpenConsole()
class Counter {
private:
  int count
  string label
public:
  static int made
  Counter(string label) { this->label = label : made++ }
  void Bump() { count++ }
  int Square(int n) {
    return n * n
  }
  string Show() { return label + ": " + Str(count) + " squared " + Str(Square(count)) }
protected:
  int Twice() { return count * 2 }
}

class Loud : Counter {
  string Show() { return UCase(super->Show()) + " twice " + Str(Twice()) }
}

Counter *c = new Counter("clicks")
c->Bump() : c->Bump() : c->Bump()
PrintN(c->Show())
PrintN(Str(Counter::made))
Counter *l = new Loud("loud")
l->Bump()
PrintN(l->Show())
delete c
delete l

Output:

clicks: 3 squared 9
1
LOUD: 1 SQUARED 1 twice 2

How a class is made

For each class x makes what a PureBasic programmer would write by hand:

  • an Interface with the class's name, holding its methods (a class that extends another extends its interface);
  • a structure holding the fields, whose first field (in the first class of a chain) is the address of the method table;
  • a procedure for each method, whose first parameter is *this;
  • the method table, in a data section.

A Static field is a global variable named Class::name, and a Static method a procedure of that name. A property is two methods, for Get and Set. An interface a class implements beside its first is a view inside the object (see Implements).

New allocates the structure with a small header in front, which is how FreeObject finds the structure's strings, lists and maps (and knows the object came from New). In front of the table is the address of the destructor chain.

So an object can be passed to code that expects the interface, and its methods called from there as usual. These names, and the hidden *this, don't appear in error messages.

Words

Class, EndClass, New, Super, this, delete, Implements, Property, Get, Set, EndProperty and C style class, new, super, private, public, get, set are only keywords where they are used as above. Programs that use them as names (new = 2, Procedure Delete(x), NewList class.s()) work as before. (Protected was a keyword already.)

Not yet available 🔜

Nothing planned for classes is missing now. Ideas for later are on the roadmap.