Privacy of member variables within the methods of other member variables
-
29-09-2019 - |
Question
Do the methods of a member variable have access to other private member variables within the same class? I have in mind a functor member variable.
Can a pointer to a private member variable be dereferenced and assigned to, outside of the class? What about in the method of another member variable?
Maybe something like
class A
{
someClass a,b;
A(){a(&b);}
}
Solution
Whenever you are calling the method of a member variable, unless its type is the class being defined, you won't have access to private member variables.
If you give access (somehow) to a pointer to a member variable, without precising that it is "const", yes, it can be dereferenced and assigned to. The same assertion is still true for the methods of other member variables.
AFTER QUESTION HAS BEEN EDITED :
In your example, you are calling a method (through member variable "a"), providing a pointer to private member variable "b". You are accessing these two private member variables in A, which is perfectly correct c++.
OTHER TIPS
At least if I understand your question correctly, the answer is no. For example, code like this:
class outer {
class inner {
int x;
};
void use_x() { inner::x = 0; }
};
...won't compile. The fact that inner
is nested inside of outer
does not give member functions of outer
any special access to the private parts of inner
.
Edit: post-edit, I don't see anything unusual at all -- A()
is (obviously) a member of class A
which also includes private members a
and b
. The definition of private
is that it's accessible (i.e., the name is visible) to code inside the class, but not to code outside the class. Since A()
is inside the class, both a
and b
are visible to it.