thecoshman
thecoshman

Reputation: 8650

C++ Friend Classes

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.

Upvotes: 3

Views: 470

Answers (2)

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.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754763

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.

Upvotes: 2

Related Questions