Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   how can i access i private data member in main (http://www.go4expert.com/forums/i-access-i-private-data-main-t12454/)

vaughn 26Jul2008 08:48

how can i access i private data member in main
 
can you give me the syntax. thanks

shabbir 26Jul2008 13:47

Re: how can i access i private data member in main
 
As far as I know you cannot access the private data??

xpi0t0s 26Jul2008 14:22

Re: how can i access i private data member in main
 
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.

faizulhaque 27Jul2008 16:33

Re: how can i access i private data member in main
 
Oh! really


All times are GMT +5.5. The time now is 03:53.