Simple Classes
2 min read
2 min read
2 min read
2 min read
2 min read
2 min read
2 min read
2 min read
2 min read
A Slice class definition is similar to a structure definition, but uses the class keyword. For example:
module M{ class TimeOfDay { short hour; // 0 - 23 short minute; // 0 - 59 short second; // 0 - 59 }}Apart from the keyword class, this definition is identical to the structure example. You can use a Slice class wherever you can use a Slice structure, except in a dictionary key type or in the type of an optional field, optional parameter, or optional return value. Marshaling and unmarshaling a class instance costs more time and space than a structure.
Unlike structures, classes can be empty:
class EmptyClass {} // OKstruct EmptyStruct {} // ErrorA class can define any number of fields, including optional fields. You can also specify a default value for a field if its type is one of the following:
- An integral type (
byte,short,int,long) - A floating point type (
floatordouble) - string
- bool
- enum
For example:
class Location{ string name; Point pt; bool display = true; string source = "GPS";}The legal syntax for literal values is the same as for Slice constants, and you may also use a constant as a default value. The language mapping guarantees that fields are initialized to their declared default values using a language-specific mechanism.