constructor called twice when creating array of object. why?

1 Ansicht (letzte 30 Tage)
Christof
Christof am 20 Jun. 2012
This is sort of a double post, as it is an issue I ran into when following a solution to a previous problem. So, sorry for that, but this really confuses me. As an example, I have a class
classdef someClass
properties
name
value
end
methods
function obj = someClass(name)
if ~nargin
% the default constructor. Needed for array creation
obj.name = '';
else
% only take care of the array part for simplicity:
if iscell(name)
[obj(1:length(name)).name] = deal(name{:});
end
end
display('object created')
end
end
end
When I run c=someClass({'a' 'b' 'c' 'd' 'e'}) I get the output object created object created
c =
1x5 someClass
Properties:
name
value
Methods
So, the constructor seems to be called twice. The second time, it is called w/o input arguments. So if I comment the blocks that checks for number of input arguments to be >0, I get the result Error using someClass (line 13) Not enough input arguments.
Error in someClass (line 14) [obj(1:length(name)).name] = deal(name{:});
when I run c=someClass({'a' 'b' 'c' 'd' 'e'}). Why does it run the constructor twice? How can I avoid that.
Thanks for any help, Chris

Antworten (1)

Daniel Shub
Daniel Shub am 20 Jun. 2012
The documentation says that "During the creation of object arrays, MATLAB might need to call the class constructor with no arguments ..." While you might be able to avoid it, I don't think it is a good idea.

Kategorien

Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by