I have made a minimal example trying to implement a clone method
classdef Person properties name; id; end methods % Constructor
function person = Person(name) person.name = name; person.id = Person.getID(); end % simple function
function name = getName(person) name = person.name; end % Simple method where Constructor is called
function person = clone(person) %want to call Constructor so even clones get unique ID
person = Person(person.name); end end methods (Static) %assign personal id (simplified version)
function id = getID() persistent max_personal_id; if(isempty(max_personal_id)) max_personal_id = 0; end max_personal_id = max_personal_id+1; id = max_personal_id; end endend
Now I try to extend the class to another class with same constructor arguments, without having to reimplement the clone method
classdef FireMan < Person methods % Constructor function person = FireMan(name) person@Person(name); end function name = getName(person) name = ['FireMan ',person.name]; end endend
But this does not give wanted functionality of the clone method as it
p = FireMan('Sam');p.getName()ans = 'FireMan Sam'p.clone.getName()ans = 'Sam'
This happens of course because I call the Person constructer in the clone method and not the Fireman Constructor
I could of course add something like this to every subclass.
function person = construct(~,name) person = FireMan(name);end
But I wonder if I could avoid changes in the subclass.
Best Answer