How to set a private property
86 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
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
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.
More Answers (0)
See Also
Categories
Find more on Whos in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!