Friend class - private member variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hairobinson
    New Member
    • Mar 2007
    • 5

    Friend class - private member variable

    How do we access the private member variable outside the class with out using friend ?
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    Originally posted by hairobinson
    How do we access the private member variable outside the class with out using friend ?
    via get() and set() methods?

    Comment

    • sanctus
      New Member
      • Mar 2007
      • 84

      #3
      Originally posted by horace1
      via get() and set() methods?
      Or just by definig any function in the class, so it will have access to the private member:
      Code:
      class exple{
      int i;
      public:
      (...)
      int fct(int x){x=i;cout<<x;}
      };
      Or something like that

      Comment

      • DhananjayNangare
        New Member
        • Mar 2007
        • 8

        #4
        You can try something like this,

        Code:
        class X
        {
        	int i;
        
        public:
        	X():i(10){};
        
        	int* fn()
        	{
        		return &i;
        	}
        };
        
        void main()
        {
        	X x;
        	int* pI = x.fn();
        	cout << *pI;
        
        	
        }
        Last edited by Ganon11; Mar 30 '07, 11:48 AM. Reason: code tags added

        Comment

        • hairobinson
          New Member
          • Mar 2007
          • 5

          #5
          Thanks guys for the response

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            Of course, providing access to the private member breaks encapsulation. That means you can no longer rely on the member functions to protect the values in the data member. So, if the value get screwed up your list of suspects exopands from just the member functions to all the function in program that can touch that data member directly or indirectly.

            Comment

            Working...