1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

how can i access i private data member in main

Discussion in 'C' started by vaughn, Jul 26, 2008.

  1. vaughn

    vaughn New Member

    can you give me the syntax. thanks
  2. shabbir

    shabbir Administrator Staff Member

    As far as I know you cannot access the private data??
  3. xpi0t0s

    xpi0t0s 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.
    class PrivTestCls
    	int a;
    	int b;
    	int c;
    	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;
    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.
  4. faizulhaque

    faizulhaque New Member

    Oh! really

Share This Page