+ 2
C/C++/Java : Access Modifier
How to access Private data members outside the class ?
7 Respostas
+ 2
In Java, you can use getters and setters.
I.e:
private int x;
int getX() { return x; }
void setX(int newX) { x = newX; }
In C++, it's about the same, with getters and setters and similar looking methods.
I actually don't know enough about C to answer that part of the question, but it's all under the same concept of "encapsulation", with getter/accessor methods and setter/mutator methods.
With encapsulation, you bundle the methods/functions of a class and it's variables together.
Often, you make some private when they don't need to be seen my members outside of the class, which, in that case for variables you still need to access outside the class, you use getter and setter methods.
+ 9
Private property in Java can be accessed using reflection.
https://code.sololearn.com/cH3IGfyhD4JJ/?ref=app
+ 9
Private property in C++ can be accessed using pointers.
https://code.sololearn.com/cD2sPG74p9B4/?ref=app
+ 7
I wouldn't ever use these techniques for production code. Maybe useful for troubleshooting purposes.
+ 3
Yeah, same in C++, setters and getters.
(I thought he was talking about accessing the members directly.)
+ 2
The point of private is to forbid exactly this!
In C++ you can define a 'friend' function to give it, like an ambassador, the permission to access the private members of that specific class.
+ 2
David Carroll, are these methods frequently used irl or are they rather used as an exception?
(It seems counterintuitive to me to do it since we went out of our way to make the fields private, but I guess there's a case for every tool...)