Static members
Some data belongs to the type rather than to any one object: a count of how
many have been made, a shared table, a setting. A static member exists
once, however many objects there are, including none.
type Ticket
declare constructor( )
declare static function Issued( ) as int32
declare static function Reset( ) as int32
declare function Number( ) as int32
private:
static issued_ as int32 '' one copy, shared by every Ticket
number_ as int32 '' one per Ticket
end type
'' A definition outside the type gives the static field its starting
'' value. Without one, it starts at 0.
dim as int32 Ticket.issued_ = 100
constructor Ticket( )
issued_ += 1
number_ = issued_
end constructor
'' A static method has no object: it is called on the type itself.
static function Ticket.Issued( ) as int32
return issued_
end function
static function Ticket.Reset( ) as int32
dim as int32 before = issued_
issued_ = 0
return before
end function
function Ticket.Number( ) as int32
return number_
end function
print "counter before any ticket:"; Ticket.Issued( )
dim as Ticket a, b, c
print "counter:"; Ticket.Issued( ); ", b is number"; b.Number( )
print "reset after"; Ticket.Reset( )
dim as Ticket d
print "d is number"; d.Number( ); ", c is still"; c.Number( )
Output
counter before any ticket: 100
counter: 103, b is number 102
reset after 103
d is number 1, c is still 103
A static field is declared in the type with static and shared by every
Ticket. Each constructor call increments the same issued_, while each
ticket keeps its own number_. The line outside the type,
dim as int32 Ticket.issued_ = 100, gives the shared field its starting
value; without it, the field starts at 0.
A static method has no object, so it has no this and cannot use
number_ or any other per-object field; it is called on the type,
Ticket.Issued( ). That is why it can answer before any ticket exists.
Reaching for a per-object field from one is refused with
TKO0937: 'number_' needs an object, and 'issued' has none: it is a static member.
Static members follow the same access rules as any other:
issued_ is private, so only Ticket's own code can change it, and the
outside world reads it through Issued( ).
A static field takes no room in an object: it is stored once, apart from them all.
Activities
- Add a static
Peak( )that reports the highest number ever issued, even after aReset. - Try to print
Ticket.issued_from outside the type, then move it to the public section and try again.