How to set a private property

86 views (last 30 days)
Ok so I'm used to c++, and in c++ a private variable (property in matlab) can be accesed by every method in that class, I'm trying to do the same here in the constructor, I want it to establish some default values if no arguments have been provided, this is my code:
classdef modulo
properties (Access=private)
A
B
R
actuadores
end
methods
function obj=modulo(BB,Actuadores)
if nargin<1
obj.B=[0,0,0];
end
if nargin<2
obj.actuadores=0;
else
obj.B=BB;
obj.actuadores=Actuadores;
end
end
end
end
But then, I do
smth=modulo
or
smth=modulo([4 3 2],5)
and I expect:
smth =
modulo with properties:
A: []
B: [0 0 0]
R: []
actuadores: 0
or
smth =
modulo with properties:
A: []
B: [4 3 2]
R: []
actuadores: 5
But instead I get:
smth =
modulo with no properties.
It works as intended when I don't set any private attributes, but how can I access those properties if I want them to be private?

Accepted Answer

Walter Roberson
Walter Roberson on 4 Aug 2017
Look at the description of Access:
"Use Access to set both SetAccess and GetAccess to the same value. "
So setting Access to private sets GetAccess to private.
Then in the description of GetAccess:
"MATLAB does not display in the command window the names and values of properties having protected or private GetAccess or properties whose Hidden attribute is true."
Therefore what you are seeing is the designed behavior for having set Access to 'private': you have told it not to display those properties when the object is displayed.
  4 Comments
Walter Roberson
Walter Roberson on 4 Aug 2017
Right, you just cannot see the properties from outside the class objects. You cannot get() private properties from outside the class objects either. From outside the class objects all you can do is bypass the security by using struct() to look at the properties.
Javi Cansa
Javi Cansa on 4 Aug 2017
Thank you, I simply created a get method myself for debug purposes, so whenever I want to see, say, B for example, I just write:
smth.get('B')
and it returns whatever is stored in B.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!