how can i access i private data member in main
|
Newbie Member
|
|
| 26Jul2008,08:48 | #1 |
|
can you give me the syntax. thanks
|
|
Go4Expert Founder
|
![]() |
| 26Jul2008,13:47 | #2 |
|
As far as I know you cannot access the private data??
|
|
Mentor
|
![]() |
| 26Jul2008,14:22 | #3 |
|
Three ways, two legal one not. 1. Call the accessor function; 2. Make main a friend of the class and access the member directly. 3. Work out the address of the member and access its memory directly.
Code:
class PrivTestCls
{
private:
int a;
int b;
int c;
public:
PrivTestCls(int _a,int _b,int _c) { a=_a; b=_b; c=_c; }
int get_a() { return a; }
friend void privtest();
};
void privtest()
{
PrivTestCls x(1,2,3);
printf("a=%d\n",x.get_a()); // we can do this without being a friend
printf("b=%d\n",x.b); // we can do this because we're a friend
// this defeats private but the syntax makes it pretty obvious that's what's happening
int *ptr2=(int*)&x;
printf("c=%d\n",ptr2[2]);
}
|
|
Skilled contributor
|
|
| 27Jul2008,16:33 | #4 |
|
Oh! really
|


