3

Just trying to make sure I have understood friends properly with this one

class A
{
  friend class B;
  int valueOne;
  int valueTwo;
  public:
  int GetValueOne(){ return valueOne; }
}
class B
{
  public:
  A friendlyData;
  int GetValueTwo(){ return friendlyData.valueTwo; }
}
main()
{
  B myObject;
  myObject.friendlyData.GetValueOne(); // OK?
  myObject.GetValueTwo(); // OK?
}

In reference to that code about, if we ignore the lack of initialising, the two functions in main would OK right? And besides doing some funky stuff, their should be no other way to get the data from these classes... To the out side of these class, B.A has no accessible data, just the member function.

thecoshman
  • 8,394
  • 8
  • 55
  • 77

2 Answers2

2

Yes the two identified calls in main are OK. They involve the access of 3 members: B::A, B::GetValueTwo and A::GetValueOne. All of which have publicaccessibility and expose no privae types. Hence they're usable from anywhere including main.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

It looks reasonable as both of the GetValueX methods are public and so the calls are fine. The call to GetValueTwo() call makes use of its friendship.

Word of warning: friendship can break the encapsulation in your design.

Flexo
  • 87,323
  • 22
  • 191
  • 272
  • 2
    Or friendship can enhance encapsulation: http://www.drdobbs.com/184401197 and http://stackoverflow.com/questions/1093618/how-does-the-friend-keyword-class-function-break-encapsulation-in-c/1093681#1093681 – Fred Larson Nov 15 '10 at 18:44
  • Very true, I was trying to find a GoTW reference discussing the issue in more depth. – Flexo Nov 15 '10 at 18:45
  • Friendship can also improve the encapsulation in your design. It depends how you use it. – aschepler Nov 15 '10 at 18:47
  • "friendship can break the encapsulation" -> according the Stroustrup, [it does not](http://www.research.att.com/~bs/bs_faq2.html#friend). – fredoverflow Nov 15 '10 at 18:53
  • Those references both argue in favour of "befriending" free functions, but they don't seem to be making a similar argument for class friendships. – Flexo Nov 15 '10 at 19:09