Calling the constructor when assigning custom classes as properties
Show older comments
Assume if have two classes like:
classdef myclass1
properties
myprop1 myclass2
end
end
and
classdef myclass2
properties
myprop2 (1,1) double = 2
myprop3 (1,1) double = 3
end
end
When creating a myclass1 object, myprop1 will be an empty myclass2 type object. It seems like the constructor of myclass2 does not get called and thus the default values do not get assigned. Is there some "shortcut" to get myprop1 set up with the intendend default values? Or do I have to explicitly state a constructor for myclass1 and make it call the constructor of myclass2?
Edit: It is actually possible to call class constructors directly from within the properties section like so:
classdef myclass1
properties
myprop1 myclass2 = myclass2
end
end
This however leads to another problem, c. f. https://mathworks.com/help/matlab/matlab_oop/expressions-in-class-definitions.html In this way, the expression (constructor) is evaluated only once when the class is first instantiated and the resulting object is then assigned to all further instances on creation. This is tricky especially if myclass2 is a handle class since in this case, subsequent changes of myprop1 values in one myclass1 object will apply to ALL myclass1 objects.
Does that sink the ship or is there yet another way I am not aware of?
[SL: Removed extraneous : from the end of the hyperlink]
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB Classes in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!