Programming Previous page   Next Page

The Class Constructor Method

The @ directory for a particular class must contain an M-file known as the constructor for that class. The name of the constructor is the same as the name of the directory (excluding the @ prefix and .m extension) that defines the name of the class. The constructor creates the object by initializing the data structure and instantiating an object of the class.

Guidelines for Writing a Constructor

Class constructors must perform certain functions so that objects behave correctly in the MATLAB environment. In general, a class constructor must handle three possible combinations of input arguments:

No Input Arguments.   If there are no input arguments, the constructor should create a default object. Since there are no inputs, you have no data from which to create the object, so you simply initialize the object's data structures with empty or default values, call the class function to instantiate the object, and return the object as the output argument. Support for this syntax is required for two reasons:

Object Input Argument.   If the first input argument in the argument list is an object of the same class, the constructor should simply return the object. Use the isa function to determine if an argument is a member of a class. See Overloading the + Operator for an example of a method that uses this constructor syntax.

Data Input Arguments.   If the input arguments exist and are not objects of the same class, then the constructor creates the object using the input data. Of course, as in any function, you should perform proper argument checking in your constructor function. A typical approach is to use a varargin input argument and a switch statement to control program flow. This provides an easy way to accommodate the three cases: no inputs, object input, or the data inputs used to create an object.

It is in this part of the constructor that you assign values to the object's data structure, call the class function to instantiate the object, and return the object as the output argument. If necessary, place the object in an object hierarchy using the superiorto and inferiorto functions.

Using the class Function in Constructors

Within a constructor method, you use the class function to associate an object structure with a particular class. This is done using an internal class tag that is only accessible using the class and isa functions. For example, this call to the class function identifies the object p to be of type polynom.

Examples of Constructor Methods

See the following sections for examples of constructor methods:


Previous page  Designing User Classes in MATLAB Identifying Objects Outside the Class Directory Next page

© 1994-2005 The MathWorks, Inc.