Search code examples
matlabreturnsubclasssuperclass

Matlab constructor of superclass after return statement


I am trying to check if a parameter is of a certain type when instantiating a subclass of a superclass, and I keep getting an error that appears to be associated with my method of checking of the argument type. The debugger won't even let me include a breakpoint without throwing the error A constructor call to superclass appears after the object is used, or after a return. I think it's pretty obvious what line of code breaks my classes, but why am I not allowed to do this type checking? What other ways are there to confirm that my arguments are of a particular type? Code below.

classdef superClass < handle
      properties
          PropertyOne
          PropertyTwo
      end    
      methods
          function sup = superClass(param1, param2)
              sup.PropertyOne = param1;
              sup.PropertyTwo = param2;
          end
      end
end
classdef subClass < superClass
      properties
          PropertyThree
      end   
      methods
          function sub = subClass(param1, param2, param3)
              if ~isa(param1, 'char')
                  disp('param1 must be type char')
                  return
              end
              sub@superClass(param1, param2);
              sub.PropertyThree = param3;        
          end
      end
end

Solution

  • Implement subClass like this:

    classdef subClass < superClass
          properties
              PropertyThree
          end   
          methods
              function sub = subClass(param1, param2, param3)
                  assert(ischar(param1),'param1 must be type char')
                  sub@superClass(param1, param2);
                  sub.PropertyThree = param3;        
              end
          end
    end
    

    You can't have the return statement before the superclass constructor runs. return would need to exit the function with an output for sub, and sub doesn't exist before the superclass constructor runs. If you use assert (or you could use if together with error instead, but assert is simpler), then it will exit with no output for sub, so it's OK.

    Also note that you don't need isa(..., 'char'), you can just use ischar.