I’m struggling through the very poorly documented OOP features of Octave, and I just wanted to share a discovery which cost me hours of time in the hopes of saving others some hours of their time.
Every branch of the constructor must create the fields of the structure in the same order, or else you’ll get a failure with the cryptic error message
error: mismatch in field names.
For example, the following very reasonable-looking constructor contains a bug:
function obj = test (a, b, c) if nargin == 0 obj.a = obj.b = obj.c = 0; obj = class(obj, "test"); elseif nargin == 3 obj.a = a; obj.b = b; obj.c = c; obj = class(obj, "test"); endif endfunction
The problem is that the
nargin == 0 branch assigns the fields in the order
a, whereas the
nargin == 3 branch assigns them in the opposite order:
a first, then
>> a = test(); >> b = test(1,2,3); error: mismatch in field names error: called from test at line 10 column 9 >>
I haven’t seen a warning about this in the documentation, but it’s my opinion that there should be!