Cannot access protected property?

18 views (last 30 days)
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

Accepted Answer

Geoff Hayes
Geoff Hayes on 28 Oct 2015
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.
  1 Comment
Jeroen Boschma
Jeroen Boschma on 29 Oct 2015
Hi Geoff,
Thanks for looking into this. I think that in the end it is simplest to have the property public instead of protected. Saves a lot of hassle and the idea I sketched still works.

Sign in to comment.

More Answers (0)

Categories

Find more on Software Development Tools in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!