Hanan Shteingart
Hanan Shteingart

Reputation: 9078

Matlab calling superclass abstract constructor syntax seems strange

I am trying to call a superclass constructor from the inheriting class. The official syntax in matlab documentation is:

obj = obj@SuperClass(ArgumentList);

However the editor seems to warn that:

the variable `obj` might be used before it is defined.

Moreover, if I try to run the code I get an error "The left operand of "@" must be the method name."

What could be wrong?

Upvotes: 0

Views: 518

Answers (1)

Hanan Shteingart
Hanan Shteingart

Reputation: 9078

I found out that this is a result of a typo of the sub-class constructor function name. Minimal reconstruction of the problem appears below:

classdef SuperDemo  < handle
    methods
        function obj = SuperDemo(opt)
            disp(['in super ', opt])
        end
    end
end

classdef SubDemo < SuperDemo
    methods
        function obj = SubDemoo(opt) % NOTICE THE TYPO SubDemoo 
            disp(['in sub ', opt])
            obj = obj@SuperDemo(opt);
        end
    end
end

If you call s = SubDemo('hello') you will get the error:

Error using SubDemo Error: File: SubDemo.m Line: 5 Column: 19 "@" Within a method, a superclass method of the same name is called by saying method@superclass. The left operand of "@" must be the method name.

This error is misleading as the left operand is obj and not SubDemo. The error message should have indicated that the construction function name SubDemoo is not the same as the class name SubDemo.

Upvotes: 1

Related Questions