MATLAB Object-Oriented Programming

(Joyce) #1

h.Data.a = rand(10,1);
end
end
function delete(h)
% Protect against accessing properties
% of partially constructed objects
if ~isempty(h.Data)
t = h.Data.a;
disp(t)
else
disp('Data is empty')
end
end
end
end


An error occurs if you call the constructor with a char vector, instead of the required cell
array:


obj = PartialObject('Test')


MATLAB passes the partially constructed object to the delete method. The constructor
did not set the value of the Data property because the error occurred when setting the
Name property.


Data is empty
Error setting 'Name' property of 'PartialObject' class:
...


When to Define a Destructor Method


Use a delete method to perform cleanup operations before MATLAB destroys the object.
MATLAB calls the delete method reliably, even if execution is interrupted with Ctrl-c or
an error.


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


For example, suppose that a method opens a file for writing and you want to close the file
in your delete method. The delete method can call fclose on a file identifier that the
object stores in its FileID property:


Handle Class Destructor
Free download pdf