Reputation: 21
I had a homework which i was asked how to access private members of a class and modify them in c++.I searched about it and i found out that we can do it with typecast and pointers which i know it's an undefined behavior and it should never be used.My question is: Is it possible to do such thing in other object oriented languages like java or python?
Upvotes: 1
Views: 265
Reputation: 1510
In C++ you can write a member function that can access and modify private members and make such function public. This is a common way for OOP. However, of course, different languages including C++ may provide hax to modify protected members in another way.
class T {
public:
int get() const {
return _member;
}
void set(int member) {
_member = member;
}
protected:
int _member;
};
List of well-known hacks
You can easily access any member in Python. Just dir
whatever you what to hack. Private members in Python.
You can hack C++ members with template http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.html . It is much safer than use pointers.
You can access private members via reflection in Java https://docs.oracle.com/javase/tutorial/reflect/.
Generally, any language that lets you debug the code should also reveal somehow protected variables.
Upvotes: 1
Reputation: 64
The C++ programming language has a friend
specifier. Friend function can see its friend class' private members. But more young languages don't include this mechanism. Because the mechanism isn't correct for object oriented programming paradigm(for encapsulation).
Upvotes: 1