Navigation bar
  Start Previous page
 115 of 206 
Next page End  

ZBasic Language Reference
107
ZX Microcontroller Family
contains all of or part of the identity string or some value to otherwise identify the object.  While this will
work, it is wasteful of space because every instance of the object will contain that data member.  A better
way to solve this problem is to add an Identify() method to the B class.  A re-written version of the
previous example appears below which has an Identify() method defined in both classes  The
m_size data member was also made Protected so that it can be accessed by subclasses such as
class B.
Class A
Public:
Enum Color
Red
Green
Blue
End Enum
Sub _Create(ByVal s as Byte = 0, ByVal c as Color = Red)
m_size = s
m_color = c
End Sub
Sub Identify()
Debug.Print "I'm an A, size="; m_size
End Sub
Protected:
Dim m_size as Byte
Private:
Dim m_color as Color
End Class
' Define a new class derived from an existing class.
Class B : A
Public:
' Define a constructor using a base class constructor.
Sub _Create(ByVal s as Byte = 0, ByVal c as Color = Red, _
ByVal w as Byte = 1) : _Create(s, c)
m_weight = w
End Sub
Sub Identify()
Debug.Print "I'm a B, size="; m_size; ", ";
Call ShowWeight()
End Sub
Sub ShowWeight()
Debug.Print "weight = "; m_weight
End Sub
Private:
Dim m_weight as Byte
End Class
Dim a1 as A = _Create(5, A::Green)
Dim b1 as B = _Create(10, B::Red, 100)
Sub Main()
Call a1.Identify()
Call b1.Identify()
End Sub
It is important to understand that when a class is derived from another class, the compiler generates code
to ensure that the base class object is fully initialized before the constructor for the derived class
Previous page Top Next page