Correct way to specify default property values when constructor uses inputParser.

38 views (last 30 days)
As per the title, I have a class where the constructor passes a varargin input argument into inputParser, which I set up by using several addParameter commands to specify name-value pairs. I see two ways to specify default values for the object's properties:
  1. Assign the default values in the properties block, say Prop1 = defaultVal1, and have addParameter take in obj.Prop1 for its defaultVal input argument, i.e. use addParameter(inputParser, 'Prop1', obj.Prop1);
  2. Do not specify default values in the properties block, and have inputParser do the assignment, i.e. use addParameter(inputParser, 'Prop1', defaultVal1).
I noticed that method 1 does not work properly if I have properties that are handle objects where the default values are calls to a constructor, i.e. Prop1 = HandleClass1(). During object creation Prop1 never calls the constructor of HandleClass1 to build a new HandleClass1 object; it is instead assigned some existing HandleClass1 object. Method 2 works fine for this, as in it does create a new HandleClass1 object and assigns it to Prop1, but I still prefer the first option because it is the convention for specifying default property values. I would like to understand at what point in time in the object creation process do the properties get instantiated with the default values and if that has any effect on how I should specify them.

Accepted Answer

per isakson
per isakson on 14 Apr 2019
Edited: per isakson on 16 Apr 2021
The default values of properties in the properties block are assigned once when the first object is created . Subsequent objects get the same values. This has important consequences when the value is an object of a handle class. One must distinguish between the underlying object and it's handle. See the descriptions in the documentation:
  1. Property Definition, Initialize Property Values
  2. Evaluation of Expressions in Class Definitions, Expression Evaluation in Handle and Value Classes
You are not the only one who has been puzzled by this behaviour. See Handle object as default class property value. (The current documentation is better than that refered to in this blog-post.)
I recommend that you use your Method 2 when the value is an object of a handle class. Method 1 will make the property in question of all objects refer to the same underlying "handle object".
  1 Comment
Hau Kit Yong
Hau Kit Yong on 15 Apr 2019
Thanks this perfectly answers my question. It is still a little unintuitive that even when a handle object constructor is specified for a property the constructor isn't actually called after the first object, but I can work around that.

Sign in to comment.

More Answers (0)

Categories

Find more on Argument Definitions 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!