Member function of a class that is friend of another and takes an object of that class as an argument

76 Views Asked by At

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;
}
1

There are 1 best solutions below

0
Ahmad Usman On

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:

void display_x(A A1) {
    cout << "Display x from class A: " << A1.x << endl;
}

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:

class B {
    int a;
    public:
        void display_x(A);
};

... 

void B::display_x(A A1) {
    cout << "Display x from class A: " << A1.x << endl;
}

Now we have it so that everything is fully declared and defined before it used, and the function will now work as expected.