MATLAB Object-Oriented Programming

(Joyce) #1

The constructor also creates an object whose properties have their default values —
either empty ([]) or the default value specified in the property definition block.


For example, this constructor operates on the input arguments to assign the value of the
Value property.


function obj = MyClass(a,b,c)
obj.Value = (a + b) / c;
...
end


Referencing the Object in a Constructor


When initializing the object, for example, by assigning values to properties, use the name
of the output argument to refer to the object within the constructor. For example, in the
following code the output argument is obj and the object is reference as obj:


% obj is the object being constructed
function obj = MyClass(arg)
obj.propert1 = arg*10;
obj.method1;
...
end


For more information on defining default property values, see “Property Default Values”
on page 8-18.


No Input Argument Constructor Requirement


There are cases where the constructor must be able to be called with no input argument:



  • When loading objects into the workspace, if the class ConstructOnLoad attribute is
    set to true, the load function calls the class constructor with no arguments.

  • When creating or expanding an object array such that not all elements are given
    specific values, the class constructor is called with no arguments to fill in unspecified
    elements (for example, x(10,1) = MyClass(a,b,c);). In this case, the constructor
    is called once with no arguments to populate the empty array elements (x(1:9,1))
    with copies of this one object.


If there are no input arguments, the constructor creates an object using only default
properties values. A good practice is to add a check for zero arguments to the class
constructor to prevent an error if either of these two cases occur:


Class Constructor Methods
Free download pdf