MATLAB Object-Oriented Programming

(Joyce) #1
Objects Passed to Functions

MATLAB passes all variables by value. When you pass an object to a function, MATLAB
copies the value from the caller into the parameter variable in the called function.

However, MATLAB supports two kinds of classes that behave differently when copied:


  • Handle classes — a handle class instance variable refers to an object. A copy of a
    handle class instance variable refers to the same object as the original variable. If a
    function modifies a handle object passed as an input argument, the modification
    affects the object referenced by both the original and copied handles.

  • Value classes — the property data in an instance of a value class are independent of
    the property data in copies of that instance (although, a value class property could
    contain a handle). A function can modify a value object that is passed as an input
    argument, but this modification does not affect the original object.


See “Comparison of Handle and Value Classes” on page 7-2 for more information on the
behavior and use of both kinds of classes.
Passing Value Objects

When you pass a value object to a function, the function creates a local copy of the
argument variable. The function can modify only the copy. If you want to modify the
original object, return the modified object and assign it to the original variable name. For
example, consider the value class, SimpleClass :

classdef SimpleClass
properties
Color
end
methods
function obj = SimpleClass(c)
if nargin > 0
obj.Color = c;
end
end
end
end

Create an instance of SimpleClass, assigning a value of red to its Color property:

obj = SimpleClass('red');

Pass the object to the function g, which assigns blue to the Color property:

5 Class Definition—Syntax Reference

Free download pdf