I'm overriding subsref and subsasgn for a class. I want to influence the behaviour of obj(…), but I can't find a good way to do this without also either breaking obj.name property access, or breaking the privacy attributes for the properties.
Examples in the documentation (see "A Class with Modified Indexing") suggest that I check the type of indexing within my subsref/subsasgn functions and call the builtin subsref/subsasgn if the type is '.'. The problem is that because these are called from a class method, the access protection on properties is overriden – so I can access and update private properties from outside the class, as if the protection was not there.
Here's an example class
classdef test properties (Access = private) x = 'ought to be private' end methods function v = subsref(M, S) switch S.type case '()' v = 'this is ok'; case '{}' error('{} indexing not supported'); case '.' v = builtin('subsref', M, S); % as per documentation
end end end end
and here's what goes wrong when I use it:
>> t = testt = test with no properties. Methods>> t(1)ans =this is ok>> t.xans =ought to be private
The attempt to access t.x should not succeed.
One solution I can think of is to write set.x and get.x methods for every single private property, to reimplement the protection that the Access attribute ought to provide.
[EDIT – added 16 hours after original post] Another possible solution: write code to analyse the subscript argument, consulting meta.property, before calling the builtin subsref/subsasgn. Not that hard, but it's ugly and probably inefficient to reimplement existing functionality.
Does anyone know a better way?
Best Answer