Extending class methods
From REALbasicWiki
| Overall article skill | ✭ |
Consider the Complex class we created in tutorial Overloading operators. One thing is missing: how do we write such class to/read from a file ? Also it may be nice if we could use Complex class with MemoryBlocks.
There are several methods to achieve that, but we will focus on the last one:
- Create a global method, e.g.
WriteComplexToBinaryStream( bs as BinaryStream, C as Complex ) - Create subclasses of BinaryStream and MemoryBlock which would have special read/write methods.
- Extend BinaryStream and MemoryBlock so that they will cope with our
Complexclass as if it was built in REALbasic.
[edit] The Extends keyword
All the magic here will be done with the REALbasic keyword Extends and, to a lesser extent, Assigns.
//In a MODULE
Function ReadComplex( extends bs as BinaryStream ) as Complex
dim realPart, ImaginaryPart as double
realPart = bs.ReadDouble
ImaginaryPart = bs.ReadDouble
return new Complex( realPart, ImaginaryPart )
End function
The extends keyword tells REALbasic that the method should be called as a_binary_stream.ReadComplex() just like built-in methods such as ReadDouble or ReadInt32. Now we can write something like:
dim f as FolderItem
dim bs as BinaryStream
dim C as Complex
f = .... //Find the file here
bs = f.OpenAsBinaryFile
C = bs.ReadComplex
The WriteComplex method is very similar:
//In a MODULE
Sub WriteComplex( extends bs as BinaryStream, C as Complex)
bs.WriteDouble C.Re
bs.WriteDouble C.Im
End sub
[edit] See also
[edit] The Assigns keyword
You may have noticed that the BinaryStream traditionally uses methods like Read... and Write... whereas, with MemoryBlocks, we use the same method name to either read or write a value:
Dim mb as MemoryBlock
Dim d as Double
mb.DoubleValue( offset ) = 2.0 //Writes the value at position (offset)
d = mb.DoubleValue( offset ) //Reads the double value at position (offset)
To be consistent with what REALbasic does, we will do the same with our Complex class:
//In a MODULE
Function ComplexValue( extends mb as MemoryBlock, offset as integer ) as Complex
Dim realPart, ImaginaryPart as Double
realPart = mb.DoubleValue( offset )
ImaginaryPart = mb.DoubleValue( offset + 8 ) //Because the size of a DoubleValue is 8 bytes
return new Complex( realPart, ImaginaryPart )
End Function
Sub ComplexValue( extends mb as MemoryBlock, offset as integer, Assigns newValue as Complex )
mb.DoubleValue( offset ) = newValue.Re //Write the real part as a double
mb.DoubleValue( offset + 8 ) = newValue.Im
End Sub
The first function is quite trivial. The second one uses the REALbasic keyword Assigns. This just tells REALbasic that we want to be allowed to use the "=" sign as if ComplexValue was a simple property.
Dim mb as MemoryBlock
Dim C as Complex
C = mb.ComplexValue( 7 ) //Get the complex value at offset 7
mb.ComplexValue( 13 ) = C //Write C into the MemoryBlock at offset 13
