how can i access i private data member in main

vaughn's Avatar, Join Date: Jul 2008
Newbie Member
can you give me the syntax. thanks
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
As far as I know you cannot access the private data??
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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]);
}
In reality if your application design requires you to access c then you must create an accessor function or make the accessing function a friend. But if the class design prevents it then you will have to negotiate with the class designer; perhaps he can suggest an alternative design that doesn't require you to access the private data.
0
faizulhaque's Avatar, Join Date: May 2008
Skilled contributor
Oh! really