MATLAB: Cannot access protected property

acessclassoopprotected property

Hi all,
The following simple test code (in 3 separate files of course…) reproduces my problem:
classdef top_class < handle
methods
function do_something(obj, fieldname)
disp(obj.(fieldname))
end
end
end
classdef derived_class < top_class
properties (Access = protected)
P
end
end
function test
clc
close all
h = derived_class;
h.do_something('P', pi)
disp('Done')
Error:
Getting the 'P' property of the 'derived_class' class is not allowed.
Error in top_class/do_something (line 4)
disp(obj.(fieldname))
The method 'do_something()' was set up this way such that users can perform some restricted operations on protected properties in all sorts of dervied classes, while the method also does a lot of things that have to do with the top-class class itself. It is important that the P-property is protected, the user is not allowed to directly modify it.
I would expect that the above structure is not a problem since P is protected, but do_something() is inherited from top_class and therefore also a method of derived_class. Why does the error occur, and more important: how can I solve this?
Thanks in advance for thinking with me,
Jeroen

Best Answer

Jeroen - I think the problem is that you are trying to access the protected member of the derived class from the base class. Look at class property attributes and consider how protected is defined as access from class or subclasses.
Generally, you can't access derived class members from the base class (though with MATLAB it seems you can if you assign access as public). Why not overload this method in the derived classes and call the base class method when needed? See calling base class methods from subclass objects for the manner in which to do this.
Related Question