Reputation:
I'm working on classes and their multiple inheritance, I have a problem which I couldn't solve after so many help, I have a class A
which is base class and class B
, which is its derive class. What I want is, the Constructor of class A
with input arguments is to be calling in derived class B
,supposed to be called in class B
with its input arguments But unfortunately i have error Not enough input arguments. as Class B
is expecting arguments but I want to give arguments as input in Class B
like above.
What solution is to be suggested or appropriate in my case?
My Code: (Base Class A)
classdef A %base class
properties
arg1
end
properties
out
end
methods
function obj = A(arg1)
obj.arg1=arg1;
obj.out=[1 2 3;];
end
end
end
Derived Class B:
classdef B < A %derived Class
properties (Access=protected)
arg2
obj1
end
methods
function obj1 = B(arg2)
obj1.arg2=arg2;
A(obj1);
end
end
end
Upvotes: 2
Views: 1023
Reputation: 30589
Call the constructor of superclass A
like this:
B.m:
classdef B < A %derived Class properties (Access=protected) arg2 end methods function obj = B(arg1,arg2) obj = obj@A(arg1); obj.arg2 = arg2; end end end
From the documentation:
By default, MATLAB calls the superclass constructor without arguments. If you want the superclass constructor called with specific arguments, explicitly call the superclass constructor from the subclass constructor. The call to the superclass constructor must come before any other references to the object.
Don't forget to clear all instances of both classes before trying new code, and clear A.m B.m
just for good measure.
Usage:
>> myA = A(1)
myA =
A with properties:
arg1: 1
out: [1 2 3]
>> myB = B(1,2)
myB =
B with properties:
arg1: 1
out: [1 2 3]
Upvotes: 3