lhcgeneva
lhcgeneva

Reputation: 1981

Vary number of inputs for superclass

B is subclass of A. I would like to call B with two arguments, as in B(arg1, arg2) and pass on arg1 to A in the constructor of B. Code looks as follows:

classdef A
properties
    arg1;
end
methods
    function a = A(arg1)
        if nargin > 0
            a.arg1 = arg1;
        end
    end
end    
end

classdef B < A  
properties
    arg2
end   
methods
    function b = B(arg1, arg2)
        b@A(arg1);
        if nargin > 0
            b.arg2 = arg2;
        end
    end
end 
end

So far, so good. Now, sometimes I would like to call B with no arguments (for example to initialize an array). Obviously calling B() throws an error, not enough inputs. Putting the call for As constructor inside the condition is also forbidden.

Is there any standard way to get around this issue, basically to be able to call the subclass with 0 and n arguments?

Cheers

Upvotes: 1

Views: 222

Answers (1)

Daniel
Daniel

Reputation: 36720

Use varargin

classdef B < A  
properties
    arg2
end   
methods
    function b = B(varargin)
        %pass all but the last argument to the super constructor
        b@A(varargin{1:nargin-1});
        if nargin > 0
            b.arg2 = varargin{2};
        end
    end
end 
end

Upvotes: 1

Related Questions