Class property automatically propagated to old class instances

1 view (last 30 days)
Dear matlab user,
I struggle with the following problem I have with my own definition for a class I use. I will illustrate the problem by means of an example. Say I define the following class:
classdef exampleClass
properties
exampleProp double {mustBeFinite(exampleProp)}
end
methods
function obj = exampleClass(exampleProp)
arguments
exampleProp = []
end
obj.exampleProp = exampleProp;
end
end
end
Now I initiate a class instance as follows:
Exmp = exampleClass(1);
I have the following issue when I copy the object.
Exmp1 = exmp;
Exmp2 = exmp;
Exmp1.exampleProp = 5;
What I would like to happen is that Exmp1 is updated and Expm,Expm2 are unchanged. However all objects now have that the exampleProp property is changed to 5. How do assure that I can change a property value without it being propagated to other class instances?
Thanks you very much!

Accepted Answer

per isakson
per isakson on 18 Jan 2022
Edited: per isakson on 18 Jan 2022
Your exampleClass is a value class. However, the behavior you describe is more like that of a handle class. See the examples below. (To run the code I need to attach the classdef-files rather than including them in this text.)
%% value class
v = exampleClass(1);
v1 = v
v1 =
exampleClass with properties: exampleProp: 1
v2 = v
v2 =
exampleClass with properties: exampleProp: 1
v1.exampleProp = 5
v1 =
exampleClass with properties: exampleProp: 5
v
v =
exampleClass with properties: exampleProp: 1
v2
v2 =
exampleClass with properties: exampleProp: 1
%% handle class
h = exampleClass_handle(1);
h1 = h
h1 =
exampleClass_handle with properties: exampleProp: 1
h2 = h
h2 =
exampleClass_handle with properties: exampleProp: 1
h1.exampleProp = 5
h1 =
exampleClass_handle with properties: exampleProp: 5
h
h =
exampleClass_handle with properties: exampleProp: 5
h2
h2 =
exampleClass_handle with properties: exampleProp: 5
  1 Comment
Luuk Spin
Luuk Spin on 18 Jan 2022
Thanks a lot! Indeed the class inherited properties from a superclass that inherited the handle class. I changed the superclass and now it works :)

Sign in to comment.

More Answers (0)

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!