Ivan
Ivan

Reputation: 153

MATLAB: Calling a superclass' method from parfor

Let us get directly to the code. There are two classes. The superclass is

classdef Parent
  methods
    function this = Parent()
    end

    function say(this, message)
      fprintf('%s\n', message);
    end
  end
end

The child class is

classdef Child < Parent
  methods
    function this = Child()
      this = this@Parent();
    end

    function say(this, message)
      for i = 1
        % This one works...
        say@Parent(this, message);
      end

      parfor i = 1
        % ... but this one does not.
        say@Parent(this, message);
      end
    end
  end
end

The question is: How to make the second loop work without introducing any additional methods? As for now, it raises an error saying "A base class method can only be called explicitly from a subclass method of the same name." Thank you.

Regards, Ivan

Upvotes: 3

Views: 2508

Answers (1)

Sam Roberts
Sam Roberts

Reputation: 24127

I think you may need to explicitly cast this to Parent before calling the parfor loop, and then call the Parent method say explicitly:

this2 = Parent(this);
parfor i = 1:1
  say(this2, message);
end

In order to do that, you need to modify the constructor of Parent to accept an input argument:

function this = Parent(varargin)
    if nargin == 1
        this = Parent();
    end
end

If Parent and Child had properties, as your real classes probably do, you would include some code following the if statement that would assign the Childs properties to the newly constructed Parent object.

Upvotes: 1

Related Questions