constructor called twice when creating array of object. why?
3 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Daniel Shub
on 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.
0 Comments
See Also
Categories
Find more on Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!