+ 4

Private name hacked

Encapsulation in C++ course : "We used encapsulation to hide the name attribute from the outside code. Then we provided access to it using public methods. Our class data can be read and modified only through those methods. " after doing some research, there is a person who showed how to access private name from outside class. Can anyone explain to me how? i know it modify memory address but i still don't get it, Why and How it can be done? See my code below : https://code.sololearn.com/c58bEXOI5rQh/?

17th May 2017, 3:03 AM
Setiawan Next
Setiawan Next - avatar
3 Answers
+ 5
When your classes are laid out in memory, their data members exist in adjacent memory addresses in the same order that you declared them in your class. In your example code, "myClass" and "Hacker" both have the string "name" as their first (and only) data member. When you create instances of either of them, the relative position of the string in memory will be the same. You can take advantage of that by casting a pointer of "myClass" to a pointer of "Hacker", and then attempting to access "name" through "Hacker" will actually access the same memory address where the string information is stored. For the record-- Don't do this. Use friend classes instead.
17th May 2017, 4:01 AM
Squidy - avatar
+ 5
Essentially, it's using the fact that C++ was an object oriented add-on to an existing language. C's pointers give you great flexibility, but are also potentially harmful to the program. What happened here is that using a generic pointer (void *), to get a reference to the object and then casting it to a different type of pointer (a pointer to the struct that was just being defined), you managed to pull a fast one on the compiler. This works mostly because C pointers are essentially ints, but ones that reference memory locations. Other OO languages were built from the ground up to avoid these kinds of shenanigans.
17th May 2017, 4:05 AM
Jim - avatar
+ 2
thanks @Squidy i will learn friend class
17th May 2017, 4:04 AM
Setiawan Next
Setiawan Next - avatar