+ 2

C/C++/Java : Access Modifier

How to access Private data members outside the class ?

3rd Apr 2019, 12:01 PM
Rugved Bodke
Rugved Bodke - avatar
7 ответов
+ 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.
3rd Apr 2019, 12:17 PM
Sheldon Duncan
Sheldon Duncan - avatar
+ 9
Private property in Java can be accessed using reflection. https://code.sololearn.com/cH3IGfyhD4JJ/?ref=app
3rd Apr 2019, 1:12 PM
David Carroll
David Carroll - avatar
+ 9
Private property in C++ can be accessed using pointers. https://code.sololearn.com/cD2sPG74p9B4/?ref=app
3rd Apr 2019, 1:56 PM
David Carroll
David Carroll - avatar
+ 7
I wouldn't ever use these techniques for production code. Maybe useful for troubleshooting purposes.
3rd Apr 2019, 2:15 PM
David Carroll
David Carroll - avatar
+ 3
Yeah, same in C++, setters and getters. (I thought he was talking about accessing the members directly.)
3rd Apr 2019, 12:18 PM
HonFu
HonFu - avatar
+ 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.
3rd Apr 2019, 12:17 PM
HonFu
HonFu - avatar
+ 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...)
3rd Apr 2019, 2:08 PM
HonFu
HonFu - avatar