34.6.5 Value Classes vs. Handle Classes

There are two intrinsically different types of classdef classes, whose major difference is the behavior regarding variable assignment. The first type are value classes:

classdef value_class
  properties
    prop1
  endproperties

  methods
    function obj = set_prop1 (obj, val)
      obj.prop1 = val;
    endfunction
  endmethods
endclassdef

Assigning an object of that class to another variable essentially creates a new object:

>> a = value_class ();
>> a.prop1 = 1;
>> b = a;
>> b.prop1 = 2;
>> b.prop1
⇒ ans =  2
>> a.prop1
⇒ ans =  1

But that also means that you might have to assign the output of a method that changes properties back to the object manually:

>> a = value_class ();
>> a.prop1 = 1;
>> a.set_prop1 (3);
⇒ ans =

<object value_class>

>> ans.prop1
⇒ ans =  3
>> a.prop1
⇒ ans =  1

The second type are handle classes. Those classes have to be derived from the abstract handle class:

classdef handle_class < handle
  properties
    prop1
  endproperties

  methods
    function set_prop1 (obj, val)
      obj.prop1 = val;
    endfunction
  endmethods
endclassdef

In the following example, the variables a and b refer to the very same object of class handle_class:

>> a = handle_class ();
>> a.prop1 = 1;
>> b = a;
>> b.prop1 = 2;
>> b.prop1
⇒ ans =  2
>> a.prop1
⇒ ans =  2

Object properties that are modified by a method of an handle class are changed persistently:

>> a.set_prop1 (3);
>> a.prop1
⇒ ans =  3

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v5.2.0/Value-Classes-vs_002e-Handle-Classes.html