| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
Examples of Class Constructors Initializing the Object Within a Constructor |
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.
The constructor has the same name as the class.
The only output argument from a constructor is the object constructed.
The constructor can return only a single argument.
If the class being created is a subclass, MATLAB calls the constructor of each superclass class to initialize the object. Implicit calls to the superclass constructor are made with no arguments. If superclass constructors require arguments, you must call them from the subclass constructor explicitly.
If your constructor makes an explicit call to a superclass constructor, this call must occur before any other reference to the constructed object.
A class does not need to define a constructor method unless it is a subclass of a superclass whose constructor requires arguments. In this case, you must explicitly call the superclass constructor with the required arguments. See Constructing Subclasses
If a class does not define a constructor, MATLAB supplies a constructor that takes no arguments and returns a scalar object whose properties are initialized to empty or the values specified as defaults in the property definitions. The constructor supplied by MATLAB also calls all superclass constructors with no arguments.
If you create a class constructor, you should implement class constructors so that they can be called with no input arguments, in addition to whatever arguments are normally required See Supporting the No Input Argument Case and Basic Structure of Constructor Methods.
Constructors must always return objects of their own class. A superclass constructor cannot return an object of a subclass.
Calls to superclass constructors cannot be conditional. This means superclass construction calls cannot be placed in loops, conditions, switches, try/catch, or nested functions. See Make No Conditional Calls to Superclass Constructors for more information.
You can restrict access to constructors using method attributes, as with any method.
The following links provide access to examples of class constructors:
Constructor functions must return an initialized object as the only output argument. The 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 and see Defining Default Values for a discussion of how best to define property values.
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
When initializing the object, for example, by assigning values to properties, 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
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 with copies of this one object. See Creating Empty Arrays for more information.
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.
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 constructor output argument and the returned object must be assigned to the constructor output argument. Here is the syntax:
classdef MyClass < SuperClass function obj = MyClass(arg) obj = obj@SuperClass(ArgumentList) ... end end
The class constructor must make all calls to superclass constructors before any other references to the object, such as assigning property values or calling ordinary class methods. Also, a subclass constructor can call a superclass constructor only once.
The constructor cannot call a superclass constructor with this syntax if the classdef does not specify the class as a superclass.
classdef MyClass < SuperClassMATLAB calls any uncalled constructors in the left-to-right order in which they are specified in the classdef line. MATLAB passes no arguments these functions.
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 cube_obj = cube(length,color,upvector,viewangle) if nargin == 0 % Provide default values if called with no arguments super_args{1} = [0 0 1]; super_args{2} = 10; else super_args{1} = upvector; super_args{2} = viewangle; end cube_obj = cube_obj@shape(args{:}); if nargin > 0 % Use value if provided cube_obj.SideLength = length; cube_obj.Color = color; end ... end ... end
If you are calling the superclass constructor from the subclass constructor and you need to support the case where you call the superclass constructor with no arguments, you must explicitly provide for this syntax.
Suppose in the case of the cube class example above, all property values in the shape superclass and the cube subclass have initial values specified in the class definitions that create a default cube. Then you could create an instance of cube without specifying any arguments for the superclass or subclass constructors. Here is how you can implement this behavior in the cube constructor:
function obj = cube(length,color,upvector,viewangle) if nargin == 0 % Create empty cell array if no input argsuments super_args = {}; else % Use specified argsuments super_args{1} = upvector; super_args{2} = viewangle; end % Call the superclass constructor with the % empty cell array (no arguments) if nargin == 0 % otherwise cell array is not empty cube_obj = cube_obj@shape(super_args{:}); if nargin > 0 cube_obj.SideLength = length; cube_obj.Color = color; end ... end
See Creating Subclasses — Syntax and Techniques for information on creating subclasses.
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.
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:
Pre-initialization — Compute arguments for superclass constructors.
Object initialization — Call superclass constructors.
Post initialization — Perform any operations related to the subclass, including referencing and assigning to the object, call class methods, passing the object to functions, and so on.
This code illustrates the basic operations performed in each section:
classdef myClass < baseClass1 properties ComputedValue end methods function obj = myClass(a,b,c) %%% Pre Initialization %%% % Any code not using first output argument (obj) if nargin == 0 % Provide values for superclass constructor % and initialize other inputs a = someDefaultValue; args{1} = someDefaultValue; args{2} = someDefaultValue; else % When nargin ~= 0, assign to cell array, % which is passed to supclass constructor args{1} = b; args{2} = c; end compvalue = myClass.staticMethod(a); %%% Object Initialization %%% % Call superclass constructor before accessing object % You cannot conditionalize this statement obj = obj@baseClass1(args{:}); %%% Post Initialization %%% % Any code, including access to object obj.classMethod(...); obj.ComputedValue = compvalue; ... end ... end ... end
See Creating Object Arrays for information on creating object arrays in the constructor.
![]() | Ordinary Methods | Creating Object Arrays | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |