constructor called twice when creating array of object. why?

1 回表示 (過去 30 日間)
Christof
Christof 2012 年 6 月 20 日
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

回答 (1 件)

Daniel Shub
Daniel Shub 2012 年 6 月 20 日
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.

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by