Search code examples
c++friend

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.


Solution

  • 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.