img

Means of accessing class properties

Operating class properties may require the implementation of specific logic for reading or writing. For example, you may need to set the variable by default, if there is an attempt to record any invalid value to it. In this case, the programmer can use the standard operator .(point) to work with objects.

To have such an access granted, it is required to implement:

  • get accessor, which is triggered while reading the variable value
  • set accessor, which is triggered while recording a value to a variable,
 class MyObject { private int realProp; int prop { get const { return realProp; } set { System.Print("Changing the value"); if(value < 0) realProp=0; else realProp = value; } } } int Run() { MyObject obj; obj.prop = -10; System.Print("Setting prop to -10. prop="+obj.prop); obj.prop = 5; System.Print("Setting prop to 5. prop="+obj.prop); return 0; } 

Output:

 Changing the value Setting prop to -10. prop=0 Changing the value Setting prop to 5. prop=5 

Note the use of the variable value, which gets the value in the beginning of recording.

Using such getters and setters does not allow to use certain operators, such as ++, --, etc., such operators must be recorded in an expanded format to carry out reading and recording separately from each other (instead of x++ you should write x=x+1).