Calling the constructor when assigning custom classes as properties

3 次查看(过去 30 天)
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]

采纳的回答

Matt J
Matt J 2023-3-12
编辑:Matt J 2023-3-12
subsequent changes of myprop1 values in one myclass1 object will apply to ALL myclass1 objects.
That is not true. You are free to overwrite the default myprop1 value with other myclass2 instances. Different instances will be independent of one another regardless of whether myclass2 is a handle or value class:
obj=myclass1;
obj.myprop1=myclass2;
Also, instead of assigning a default myprop1 value, you could write a constructor for myclass1 which assigns a fresh, independent myclass2 instance every time it is called:
classdef myclass1
properties
myprop1
end
methods
function obj=myclass1
obj.myprop1=myclass2;
end
end
end
  2 个评论
broken_arrow
broken_arrow 2023-3-12
Thanks Matt. So it comes down to calling the myclass2 constructor from within the myclass1 constructor.
Regarding your remark on the assignment of a new object: Of course one can do that, but using the method I referred to will lead to the behavior I described. Just wanted to point it out because I think it's a bit counterintuitive (I didn't know about that behavior before).
Steven Lord
Steven Lord 2023-3-12
See this documentation page for a little more information on some of the considerations you need to account for when creating objects whose properties contain other objects.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by