addprop Adds Properties To Multiple Instances?
Show older comments
I have a class defintion similar to the following:
classdef A < hgsetget & dynamicprops
%...
end
Then I have another class defintion similar to the following
classdef B < hgsetget
properties
a = A();
b = A();
end
end
Now here is where it gets weird I, I wrote the following code:
r = B();
e = B();
addprop( get( r, 'a' ), 'p' );
%These two have p.%
disp( properties( get( r, 'a' ) ) );
disp( properties( get( e, 'a' ) ) );
%But these two do not.%
disp( properties( get( r, 'b' ) ) );
disp( properties( get( e, 'b' ) ) );
I double checked the documentation, it states that 'addprop()' adds a property to a class instance. I have taken a few steps after this but none have really worked to well. Could someone explain this behavior to me, or how to work around it, or fix it?
P.s I am using MATLAB R2011b. P.s.s I am a tad new to MATLAB, please excuse any "nooby - ness".
Accepted Answer
More Answers (1)
Jim Hokanson
on 10 Aug 2013
It seems like you have two different issues going on, first, from your question:
classdef B < hgsetget
properties
a = A();
b = A();
end
end
'a' and 'b' point to different objects, so modifying the properties in 'a' will not change 'b', since they are different instances, and addprop modifies instances, not class definitions. So I would expect that 'b' doesn't have a 'p' property.
From your answer you bring up another issue which was non-obvious to me as well at one point. Matlab evaluates the default properties of each class once unless it is redefined. This means that in your example code (from the original question) 'a' and 'b' will only ever point to two objects, and creating a new B() will not give you new instances.
See the following post under 'defaults': http://blogs.mathworks.com/loren/2011/03/08/common-design-considerations-for-object-properties/#10
Final note, I'm surprised your answer doesn't throw a recursion overflow error, perhaps you meant to assign A() to the properties in the constructor?
Categories
Find more on Data Type Identification in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!