Reset method being called twice during instantiation of a class instance with inheritance
9 views (last 30 days)
I'm defining various classes with an inheritance hierarchy and having problems setting up each class's reset method so that it is only called once during instantiation. Here is a toy-example which illustrates the problem.
classdef MySuperClass < matlab.mixin.Copyable
function obj = MySuperClass(a0)
obj.a0 = a0;
disp(" MySuperClass reset()") % for debugging
obj.a = obj.a0;
classdef MyClass < MySuperClass
function obj = MyClass(a0, b0)
obj = obj@MySuperClass(a0);
obj.b0 = b0;
disp(" MyClass reset()") % for debugging
obj.b = obj.b0;
The reason I want to call the reset method during instantiation is that the reset operations are quite extensive in the actual implementation and therefore I don't want to duplicate the code in two places or have it run twice.
% Test class instantiation
disp("1. Instantiate MySuperClass")
x1 = MySuperClass(0.1); assert(x1.a == 0.1);
x1.a = x1.a + 1;
disp("2. Reset MySuperClass")
x1.reset(); assert(x1.a == 0.1);
disp("3. Instantiate MyClass")
x2 = MyClass(0.1, 0.2); assert(isequal([x2.a x2.b], [0.1 0.2]));
x2.a = x2.a + 1;
x2.b = x2.b + 1;
disp("4. Reset MyClass")
x2.reset(); assert(isequal([x2.a x2.b], [0.1 0.2]));
This executes without errors but it is evident that the reset methods are called twice when instantiating MyClass as shown in the output after '3. Instantiate MyClass' below:
Test script output:
1. Instantiate MySuperClass
2. Reset MySuperClass
3. Instantiate MyClass
4. Reset MyClass
I think this is happening because the two lines obj = obj@MySuperClass(a0) and obj.reset() in MyClass.m are both calling reset@MyClass rather than the local methods.
What is the correct way to define these two classes so the reset methods are only called once when an object is instantiated?
Ishan Gupta on 27 Jul 2022
Calling obj.reset() in the constructor of MyClass is redundant.
This is because while calling obj@MySuperClass(a0); you also call obj.reset() in the superclass constructor here the reset method is already overridden hence reset of MyClass.
In summary obj@MySuperClass(a0); and obj.reset() in MyClass constructor are calling the same reset function of MyClass.
Solution : eliminate obj.reset()