Is it possible to have two classes A & B such that the member function of A is a friend function of B and takes an instance of B for an argument?
Is the same possible for constructors of A and B too?
#include <iostream>
using namespace std;
class A;
class B {
int a;
public:
void display_x(A A1) {
cout << "Display x from class A: " << A1.x << endl;
}
};
class A {
int x, y;
public:
void set_x() { x = 10; y = 20; }
friend void B::display_x(A);
};
int main()
{
A A1;
A1.set_x();
B B1;
B1.display_x(A1);
return 0;
}
This is possible once you rearrange the code so that everything is declared and defined properly. In c++ the compiler needs to see the definition of a class before it can access members of that class. Here you have it so that the class B is using a parameter of class A and accessing its member variable before that variable even exists in a definition of class A:
To fix this we can instead only declare the function inside class B at this point and move the actual definition of the function down after the class A is fully defined:
Now we have it so that everything is fully declared and defined before it used, and the function will now work as expected.