0

I wanted to know if there's any exsisting solution to the problem:

class b;
class a {
  int x;

 public:
  friend class b;
  a() { x = 5 }
  void print(b obj) {
    cout << x << endl;
    cout << obj.y << endl;
  }
};

class b {
  int y;

 public:
  friend class a;
  b() { y = 10 }
  void print(a obj) {
    cout << y << endl;
    cout << obj.x << endl;
  }
};

"This is giving me an issue since class b body is not define before class a, so what is there any easy and existing way to make it work?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Implement the member functions that require the forward declaration in a cpp file. – drescherjm May 28 '21 at 16:47
  • Move the definition of `print` outside of the class definition. It can be inline in the header, after the definition of `b`, or it can be in a cpp file. – Pete Becker May 28 '21 at 16:49
  • 2
    This isn't about friendship; the problem isn't access control, it's that the definition of `b` has to come before code that uses it. – Pete Becker May 28 '21 at 16:50
  • At `cout << obj.y << endl;` in `A::print`, not enough is known about `B` to be able to access `B`'s `y` member. All `A` knows is there's class named `B`, not what's in `B`. If you define `A::print` outside the class definition and after `B` has been fully defined, the problem will go away. – user4581301 May 28 '21 at 16:55

1 Answers1

2

For starters you forgot to place a semicolon after these statements

x = 5

and

y = 10

You can define member functions that access data members of other class when the other class is defined that is when it is a complete type.

So place the definition of the function print of the class a after the definition of the class b.

For example

#include <iostream>
using namespace std;

class b;

class a {
  int x;

 public:
  friend class b;
  a() { x = 5; }
  /* inline */ void print(b obj);
};

class b {
  int y;

 public:
  friend class a;
  b() { y = 10; }
  void print(a obj) {
    cout << y << endl;
    cout << obj.x << endl;
  }
};

  void a::print(b obj) {
    cout << x << endl;
    cout << obj.y << endl;
  }

int main() 
{
    a a;
    
    a.print( b() );
    
    b b;
    
    b.print( ::a() );

    return 0;
}

The program output is

5
10
10
5

You could place the class definitions with member function declarations in a header and then define the member functions in a cpp file.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335