0

Possible Duplicate:
Is it possible to access private members of a class?

Is it possible to change PRIVATE data memebers of a CLASS without Member function or Friend function,by creating object of that class and accessing address of that created object,is it possible to some how modify PRIVATE data members using such POINTERS if we know the address of that class???

Community
  • 1
  • 1
aj8080
  • 95
  • 1
  • 8
  • Changing class definition is way less hassle. Also, don't write code like this. – Cat Plus Plus Sep 29 '11 at 16:16
  • 1
    Yes, it's possible. Why would you do it? – a1ex07 Sep 29 '11 at 16:17
  • 1
    Dupe of [this](http://stackoverflow.com/questions/729363/is-it-possible-to-access-private-members-of-a-class), [this](http://stackoverflow.com/questions/3467261/can-i-trick-access-to-private-c-class-member-variables) and [this](http://stackoverflow.com/questions/726096/accessing-private-members/726304#726304) – Alex Sep 29 '11 at 16:19
  • @cicada so how to make our program robust ?? inorder to save it from such memory address manipulation ?? – aj8080 Sep 29 '11 at 16:22
  • @alex i dint know it was dupe buddy,anyways thanks for the link. – aj8080 Sep 29 '11 at 16:23
  • @aj8080: Have a talk with whoever checked in such ridiculous code into your repository. `public`/`private` is not a *security* feature, its a compiler feature to help the programmer respect a class's (hopefully documented) API. Nothing prevents someone from writing that cast, or just `memset(&obj, 0, sizeof(obj))`. Both are undefined behavior, of course, and should be immediately clear are bad ideas – derobert Sep 29 '11 at 16:25

2 Answers2

4

Assuming you know the in-memory layout of the class fields, it is indeed possible to change its private members using something like *((FieldType*)((char*)&object + fieldOffset)) = someValue;.

You shouldn't do this. It's criminal.

user703016
  • 37,307
  • 8
  • 87
  • 112
1

The language is not there to police you but rather to keep you from making mistakes. You can do a set of different things to gain access to the private fields, but at the end of the day, none of them is a good idea on the premise that if the class is yours, you can provide access in a sensible way, and if it is not yours, all private members are implementation details that can change from one version to another and there are most probably invariants of the class that you might or not know and could break if you modify those members.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489