MATLAB Object-Oriented Programming

(Joyce) #1

Exclude Properties from Copy


Use the NonCopyable property attribute to indicate that you do not want a copy
operation to copy a particular property value. By default, NonCopyable is false,
indicating that the property value is copyable. You can set NonCopyable to true only on
properties of handle classes.

For classes that derive from matlab.mixin.Copyable, the default implementation of
copyElement honors the NonCopyable attribute. Therefore, if a property has its
NonCopyable attribute set to true, then copyElement does not copy the value of that
property. If you override copyElement in your subclass, you can choose how to use the
NonCopyable attribute.

Set the Attribute to Not Copy

Set NonCopyable to true in a property block:

properties (NonCopyable)
Prop1
end

Default Values

If a property that is not copyable has a default value assigned in the class definition, the
copy operation assigns the default value to the property. For example, the CopiedClass
assigns a default value to Prop2.

classdef CopiedClass < matlab.mixin.Copyable
properties (NonCopyable)
Prop1
Prop2 = datestr(now) % Assign current time
end
end

Create an object to copy and assign a value to Prop1:

a = CopiedClass;
a.Prop1 = 7

a =

CopiedClass with properties:

7 Value or Handle Class — Which to Use

Free download pdf