Weird class property behavior

1 view (last 30 days)
Tim
Tim on 6 Apr 2020
Commented: Tim on 7 Apr 2020
Hi all,
I have noticed that if one defines a property within a class, as an object of another class that inherits from the handle class,
then if a class method changes that property, it gets changed for every instance of the original class. Example:
classdef DataStruct < handle
properties
x
end
methods
function obj = DataStruct()
obj.x = 0;
end
function preAllocate(obj, len)
% Changing the property through class method:
obj.x = zeros(1,len);
end
end
end
classdef MyClass
properties
my_var = DataStruct()
end
methods
function obj = MyClass()
disp('Superclass initiated');
end
function preAllocate(obj, val)
% Changing the property through class method:
obj.my_var.preAllocate(val);
end
end
end
Main:
object1 = MyClass();
object2 = MyClass();
object1.preAllocate(5);
% At this point, object1.my_var is a row of 5 zeros,
% but also object2.my_var had been changed to that.
In fact, the my_var value of ANY instance of this class AND ANY instance of its subclass(es) gets changed.
The ways to fix this is either through not inheriting from handle (which raises other issues), or declare the properties just by name, and then assigning values inside the constructor. Actually, after running the code above, calling preAllocate() from one instance will change the value of my_var of the other instance, yet calling object1/2.my_var = Datastruct(), even once, would break this cycle - any calls to preAllocate() from now on will only change the value of the instance it was called upon.
This took me quite a while to realize. Is it by design? if so, people should not be encouraged to assign default values to class properties before of the constructor. If I was using this system the wrong way, please let me know as well.
Many thanks, Tim.
BTW Using Matlab R2017a

Accepted Answer

Steven Lord
Steven Lord on 6 Apr 2020
Yes, this is documented behavior. See the "Expressions In Handle Classes" section on this documentation page and the "Initializing Properties to Handle Objects" section on this documentation page.
  1 Comment
Tim
Tim on 7 Apr 2020
Thank you, I can see the explanation on that. Quite an elusive one ;)

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!