Main Content

Dynamic Properties and ConstructOnLoad

Setting the class ConstructOnLoad attribute to true causes MATLAB® to call the class constructor when loading the class. MATLAB saves and restores dynamic properties when loading an object.

If you create dynamic properties from the class constructor, you can cause a conflict if you also set the class ConstructOnLoad attribute to true. Here is the sequence:

  • A saved object saves the names and values of properties, including dynamic properties

  • When loaded, a new object is created and all properties are restored to the values at the time the object was saved

  • Then, the ConstructOnLoad attribute causes a call to the class constructor, which would create another dynamic property with the same name as the loaded property. See Save and Load Objects for more on the load sequence.

  • MATLAB prevents a conflict by loading the saved dynamic property, and does not execute addprop when calling the constructor.

If you use ConstructOnLoad, add dynamic properties from the class constructor, and want the constructor to call addprop at load time, then set the dynamic property Transient attribute to true. This setting prevents the property from being saved. For example:

classdef (ConstructOnLoad) MyClass < dynamicprops
   function obj = MyClass
      P = addprop(obj,'DynProp');
      P.Transient = true;

Related Topics