MATLAB: Do I receive an error when I reference a property of a handle class that contains another property of the same class

MATLAB

Suppose I have two handle classes, 'super' and 'sub', defined as follows.
'super' is a handle class has two properties. Of these,
* 'subObject' holds an instance of 'sub' and has attributes (Access = public).
* 'CellArray' is a cell array that points to the other property 'subObject' in its first element. This property has attributes (SetAccess = private, GetAccess = public).
classdef super < handle
properties (Access = public)
subObject
end
properties (SetAccess = private, GetAccess = public)
CellArray
end
methods
function obj = super()
obj.subObject=sub();
obj.CellArray{1}=obj.subObject;
end
end
end
'sub' is a handle class that has one property:
* 'theString' holds a character array.
classdef sub < handle
properties (Access = public)
theString
end
methods
function obj = sub()
obj.theString = 'MATLAB';
end
end
end
Finally, when I get inconsistent results with the following syntax for try to modify the value of 'CellArray' in a 'super' object:
For instance, the following syntax throws an error:
clear all;
clear classes;
o = super();
o.CellArray{1}.theString % To check the initial property;
o.CellArray{1}.theString = 'something else'
??? Setting the 'CellArray' property of the
'super' class is not allowed.
Error in ==>
o.CellArray{1}.theString = 'something else'
However, when I try to do the same with the following syntax, breaking up the single line into a multipart snippet, I receive no error, but the value still changes to 'something else':
clear classes;
o = super();
o2 = o.CellArray{1};
o2.theString
o2.theString = 'something else';

Best Answer

This is not a bug in MATLAB, but expected behavior. If this is not desired behavior in your application, consider defining the classes as value classes, rather than handles classes.
In both cases, the underlying value 'theString' is changed and this is to be expected even though it happens through the 'SetAccess=private' attributed property 'CellArray'. This is because the contract that the user has with the super class states that the property 'theString' can be modifiable per its 'SetAccess=public' attribute, regardless of whether it was called through CellArray or not. This is the inherent nature of handle classes and this is intended to be the case.
In the first calling syntax,
o.CellArray{1}.theString = 'something else'
the error is thrown as a courtesy to inform the user that CellArray{1} should not be modified directly.
The code parser in MATLAB still considers these lines as separate executions, similar to the second calling syntax, even when it is inlined as one expression. Since the right-hand side of the expression (....theString = 'something else') is executed first, the value of the 'theString' property gets modified even before the parser realizes that it is referenced through another 'SetAccess=private' property.