File Exchange

image thumbnail

Copy / Clone method for handle and hgsetget class

version 1.0.0.0 (4.29 KB) by Sebastian Hölz
Enable deep copying of child objects of classes handle or hgsetget

1 Download

Updated 25 Jan 2012

View License

The handle or hgsetget classes miss a method to make deep copies of objects. The two classes "handleplus" and "hgsetgetplus" take care of this.

To use these classes, ...
- simply put them somewhere on your Matlab path.
- in classdef-files change instances of
"classdef MyClass < handle" (or hgsetget)
to
"classdef MyClass < handleplus" (or hgsetgetplus)

Suppose you have defined a "MyClass" as child of "handleplus". Deep copies are now created as follows:
>> OBJ = MyClass;
>> OBJ_new = OBJ.copy;

Some short notes:
- This implementation (hopefully) also handles deep copying of inherited private or protected properties (s. discussion "Clone Handle Object - using MATLAB OOP" -> link in acknowledgments).
- It handles properties, which contain handle-objects
- It does not handle cyclic references (s. mathforum.org/kb/message.jspa?messageID=7629086&tstart=0)

Please read the help for these files for more details and report any bugs.

Cheers

Sebastian

Cite As

Sebastian Hölz (2020). Copy / Clone method for handle and hgsetget class (https://www.mathworks.com/matlabcentral/fileexchange/34762-copy-clone-method-for-handle-and-hgsetget-class), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (1)

The problem is this class cannot handle the copy of protected/private properties defined by the classes which derive from it. Thus we need to declare public all the properties of the children classes and so forget encapsulation...

It is not a criticism, there is no way to reach private and protected properties of a subclass from its superclass, so you cannot do better :)

MATLAB Release Compatibility
Created with R2011b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired by: Clone Handle Object - using MATLAB OOP