How to access one private member in another class?

I am new to OOP. I am writing a class (call it ClassA) which needs access to just 1 private member in ClassB. How to I go about doing this? There is concept of friend functions and friend classes which I do not fully understand at this point.
All I want is that there be a function inside ClassA which is private to it and is only used within it, which can read 1 specific private member in ClassB.
1
2
3
4
5
6
7
class B
{
  public:
     int getValue() { return value;}
  private:
      int value;
}


Your function in classA can call B::getValue() and in doing so read the value of the private member.

Yes, but how do I make it such that only classA can modify this private member of classB and no other class? I mean if I just created a function changevalue(int x) then any class can call this function and change value of this specific private stored inside the classB.
You're looking for the keyword "friend".

1
2
3
4
5
6
class B
{
  friend class A;
  private:
      int value;
}


Now, any object of type A can freely access B::value

http://www.cplusplus.com/doc/tutorial/inheritance/

However, you cannot limit it to JUST that one private value. If you want to do that, it's not simple. You're looking at something like this:

http://stackoverflow.com/questions/16055616/allowing-a-friend-class-to-access-only-some-private-members
Last edited on
Topic archived. No new replies allowed.