Class Constructor Methods

Rules for Constructors

A constructor method is a special function that creates an instance of the class. Typically, constructor methods accept input arguments to assign the data stored in properties and always return an initialized object.

Initializing an Instance Within a Constructor

Constructor functions must return an initialized object as the first output argument. The first output argument is created when the constructor executes, before executing the first line of code.

For example, the following constructor function can assign the value of the object's property A as the first statement because the object obj has already been assigned to an instance of myClass.

function obj = myClass(a,b,c)
   obj.A = a;
      ...
end

You can call other class methods from the constructor because the object is already initialized.

The constructor also creates an object whose properties have their default values—either empty ([]) or the default value specified in the property definition block. See Property Definition Block for a description of this syntax.

For example, the following code calls the class method CalculateValue to assign the value of the property Value.

function obj = myClass(a,b,c)
   obj.Value = obj.CalculateValue(a,b);
      ...
end

Referencing the Object in a Constructor

When initializing the object by assigning values to properties, and so on, you must 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

Supporting the No Input Argument Case

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

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

function obj = myClass(a,b,c)
   if  nargin > 0
      obj.A = a;
      obj.B = b;
      obj.C = c;
      ...
   end
end

See Basic Structure of Constructor Methods for ways to handle superclass constructors.

Constructing Subclasses

Subclass constructor functions must explicitly call superclass constructors if the superclass constructors require input arguments. The subclass constructor must specify these arguments in the call to the superclass constructor using the following syntax:

function obj = myClass(arg)
   obj = obj@SuperClassName(ArgumentList)
      ...
end

Any uncalled constructors are called in the left-to-right order that they are specified, but no arguments are passed to these functions.

No Conditional Calls to Superclass Constructors

Calls to superclass constructors must be unconditional and you can have only one call for any given superclass. You must initialize the superclass portion of the object by calling the superclass constructors before you can use the object (for example., to assign property values or call class methods).

In cases where you need to call superclass constructors with different arguments, depending on some condition, you can conditionally build a cell array of arguments and provide one call to the constructor.

For example, in the following example the superclass shape constructor is called using some default values when the cube constructor has been called with no arguments:

classdef cube < shape
   properties
      SideLength = 0;
      Color = [0 0 0];
   end
   methods
      function obj = cube(length,color,upvector,viewangle) 
         if nargin == 0 % Provide default values if called with no arguments
            args{1} = [0 0 1];
            args{2} = 10;
         else
            args{1} = upvector;
            args{2} = viewangle;
         end
         obj = obj@shape(args{:});
         if nargin > 0 % Use value if provided
            obj.SideLength = length;
            obj.Color = color;
         end
      ...
   end
   ...
end

More on Subclasses

See Creating Subclasses — Syntax and Techniques for information on creating subclasses.

Errors During Class Construction

If an error occurs during the construction of a handle class, the MATLAB class system calls the class destructor on the object along with the destructors for any objects contained in properties and any initialized base classes.

See Handle Class Delete Methods for information on how objects are destroyed.

Basic Structure of Constructor Methods

It is important to consider the state of the object under construction when writing your constructor method. Constructor methods can be structured into three basic sections:

This code illustrates the basic operations performed in each section:

classdef myClass < baseClass1
   methods
      function obj = myClass(a,b,c)

% Pre Initialization
% Any code not using first output argument (obj)
         if nargin == 0
            args{1} = x;args{2} = y;
            a = z;
         end
         compvalue = myClass.staticMethod(a);

% Object Initialization
% Call base-class constructor before accessing object
         obj = obj@baseClass1(args{:});

% Post Initialization
% Any code, including access to object
         obj.classMethod(...);
         obj.Property = compvalue;
         ...
      end
      ...
   end
   ...
end

See for information on creating object arrays in subclass constructors.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS