I think what Adam said here is the key:
but it knows it is creating this as part of creating the subclass
In other words, the 'obj' output of the myclass() constructor is not an ordinary output variable. Not only is it pre-initialized when the myclass workspace is entered, but the pre-initialization type also depends on how myclass() was invoked. If it was invoked using a subclass object, as in subclassObj@myclass() then obj is pre-intialized to the subclass type. This is confirmed by the following,
classdef myclass
methods
function obj=myclass
disp ' '
disp(['obj is a ' class(obj) ' object'])
disp ' '
end
end
end
classdef mysubclass < myclass
methods
function obj=mysubclass
obj=obj@myclass;
end
end
end
which gives the behavior:
>> myclass;
obj is a myclass object
>> mysubclass;
obj is a mysubclass object
And therefore, assigning obj a superclass object, even in the superclass constructor, can force it to be the wrong type.
Best Answer