>Isn't the above code shows flaw/hole in the language??
No. If C++ were designed to avoid both stupid breaking of the rules
and willful/malicious breaking of the rules, the language would be a beast that nobody wanted to use. C++ protects you from your stupidity, but if you know how to sidestep the protection, that's your business.
>How can i change the private data member j through the typecasted pointer
#include <iostream>
using namespace std;
class emp {
int i;
int j;
public:
emp(): i ( 10 ), j ( 20 ) {}
void display()
{
cout<< i <<' '<< j <<'\n';
}
};
int main()
{
emp e;
unsigned char *p =
reinterpret_cast<unsigned char*> ( &e );
int *pi =
reinterpret_cast<int*> ( p );
int *pj =
reinterpret_cast<int*> ( p + sizeof ( int ) );
e.display();
++*pi;
--*pj;
e.display();
return 0;
}
That's one way you
can, since you asked. But you shouldn't. Private members are private for a reason, and you should respect that. Not to mention that if you have to ask about this, you're probably not aware of the many (many!) pitfalls and potential undefined behavior of what you want to do.
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Offline 11,807 posts
since Sep 2004