Matlab copy constructor

copy-constructor, matlab, oop

Solution

If you want a quick-and-dirty solution that assumes all properties can be copied, take a look at the PROPERTIES function. Here's an example of a class that automatically copies all properties:

classdef Foo < handle
  properties
    a = 1;
  end
  methods
    function F=Foo(rhs)
      if nargin==0
        % default constructor
        F.a = rand(1);
      else
        % copy constructor
        fns = properties(rhs);
        for i=1:length(fns)
          F.(fns{i}) = rhs.(fns{i});
        end
      end
    end
  end
end

and some test code:

f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value.

Problem

Is there a better way to implement copy construcor for matlab for a handle derived class other than adding a constructor with one input and explicitly copying its properties? ``` obj.property1 = from.property1; obj.property2 = from.property2; ``` etc. Thanks, Dani

Original source