how can i access i private data member in main

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

  1. vaughn

    vaughn New Member

    Joined:
    Jul 26, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    can you give me the syntax. thanks
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    As far as I know you cannot access the private data??
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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.
     
  4. faizulhaque

    faizulhaque New Member

    Joined:
    May 23, 2008
    Messages:
    210
    Likes Received:
    3
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Karachi
    Home Page:
    http://www.google.com

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice