1

Is it possible to make Matlab to call a copy method of my class TMyClass (which is a handle calss) when an object of this class is assigned to a variable. In other words, I want my handle class to behave as a value class when copying it:

obj = TMyClass(); %// has method "copy", which returns a deep copy of the object
%// Now, if I write this ...
obj_copy = obj;   
%// ... I want Matlab to do in fact this:
obj_copy = obj.copy; %// 

As I understood, there is no way to override the = operator in Matlab. Is there any other workaround to do so?

Thanks!

Oleg
  • 111
  • 9
  • (Since I'm not sure if this is possible,) What is the intended use case or reason for this desired behavior? There may be other ways of solving the problem other than parent coercion. – TroyHaskin Aug 24 '15 at 23:01
  • The background of the problem is following. I have a structure describing some data, and _many_ functions processing this structure. Now I want to write a class (instead of the structure) which stores and manipulates that data, and it should be descendant of `dynamicprops` class. But I don't really want to modify all the functions (compatibility issues), which work with the structure and assume copy-by-value semantic. – Oleg Aug 24 '15 at 23:27
  • 1
    Gotcha. Two more questions. (1) Are the functions performing some destructive alterations to their local struct that this is needed? (2) The requirement for a `handle` class comes from the inheritance of `dynamicprops` by `TMyClass`; is there a way to avoid this (I can only see the need for that parent if you need to add properties to an instance in other classes/functions aware of `TMyClass`'s nature through `addprop`)? – TroyHaskin Aug 25 '15 at 00:03
  • (1) yes, there are plenty operations in the functions like `MyStruct.field = some_value`, which assumes that `MyStruct` is a copy of the original one passed as an argument. (2) Indeed, an inheritance from `dynamicprops` is required because of need to add/remove properties dynamically. The problem is that I want all functions to work with old structures as well. The simplest solution I came to so far is to add a checking to each function: if the argument is an object then create a copy of it. But maybe there is more elegant solution... – Oleg Aug 25 '15 at 11:24

1 Answers1

0

If you have a value class, then obj_copy = obj will create a new copy of your object. For a handle class you always have to call a copy function yourself. I had the same issue already and would suggest you do a copy method as you proposed.

Depending on your design and what you want to do with it you could also go crazy and use fluent interfaces. In my case I had an object conaining data which returned filtered copies of itself in such a way:

obj = DataObject()
f1 = obj.getByType('pressure') % f1 ~= obj
f2 = f1.getByTemperature(@(x) x < 10) % using an anonymous function for filtering, also f2 ~= f1
Benjamin
  • 68
  • 7