954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to avoid the situation

#include
#include
class A
{
int a;
public:
A()
{
a=100;
}

int get()
{
return a;
}
};

int main()
{
A *a=new A();
int *p=(int *)a;

printf("%d\n",a->get());

*p=200;

printf("%d\n",a->get());

system("pause");
}

its out put is -
100
200

so can any body help me to avoid this situation bcoz as we can observ the class definition we can access the private members.

vivekgalatage
Newbie Poster
6 posts since Aug 2004
Reputation Points: 12
Solved Threads: 0
 

What are you trying to avoid? Hacking? You hacked this and claim that you can access the private member a->a; All the 'private' designation means is that you can't access it via referencing it normally in the compiler; there's no implied protection of the memory area.

Try "a->a = 200;" and the compiler will tell you that you can't access a private member. That is a COMPILE time protection; what you demonstrated is a RUNTIME access.

Incidentally, add this to your definition of the class A:

virtual ~A() { a = 0; }

and try your hack. The output will read 100 and 100 and then your program will crash, because the vtable pointer for the destructor was set to 200.

Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You