Reputation: 290
I have following code that can access and change private member outside the class
#include<iostream>
#include<conio.h>
using namespace std;
class Test
{
private:
int data;
public:
Test() { data = 0; }
int getData() { return data; }
};
int main()
{
Test t;
int* ptr = (int*)&t;
*ptr = 10;
cout << t.getData();
getch();
return 0;
}
It is basically against encapsulation .. I wish to know why such a technique exist to access private members? how this is happening beneath .. please explain???
If such a technique is there what's the use of making a member private??
Upvotes: 1
Views: 208
Reputation:
Short answer: It doesn't work.
Why "works"?
The size of your object is 4 bytes (cout << size(t);
), which is the size of the integer.
This is why this appears to work, when you say this int* ptr = (int*)&t;
, you are saying that this 4 bytes of t
will be 4 bytes of int
.
Beneath the code
This class is a POD (ignoring the constructor) (see more)
The function int getData() { return data; }
, is inlined by the compiler (I'm not sure) so return data
returns the value of *ptr
not data
.
Test it with int getData() { cout << data; }
and you will that ptr
never touch the value data. This is called undefined behavior.
If your class has this private members (example):
int foobar;
int data;
Then your t
class has the size of 8 bytes, and when converting t
to int
, you're getting the first 4 bytes, which is the variable foobar (see more). And this line cout << t.getData();
will return 0, which is the value specific in the constructor.
Upvotes: 0
Reputation: 5741
Because C++ protects against accident rather than deliberate circumvention (fraud). Only hardware can protect against malicious use of a general-purpose language, and even that is hard to do in realistic systems.
Mentioned by Bjarne Stroustrup in his book "The C++ Programming Language".
Upvotes: 3