Search code examples
c++forward-declarationfriend-function

Forward declaration with friend function: invalid use of incomplete type


#include <iostream>

class B;

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

class B{
 int b;
public:
 void frndA();
};

void B::frndA(){
 A obj;
 std::cout << "A.a = " << obj.a << std::endl;
}

int main() {
 return 0;
}

When trying to compile this code, some errors occurred. E.g.

invalid use of incomplete type

What are the problems in this code?


Solution

  • Place the whole of the class B ... declaration before class A. You haven't declared B::frndA(); yet.

    #include <iostream>
    using namespace std;
    
    class B{
        int b;
    public:
        void frndA();
    };
    
    class A{
        int a;
    public:
        friend void B::frndA();
    };
    
    
    
    void B::frndA(){
        A obj;
        //cout<<"A.a = "<<obj.a<<endl;
    }
    
    int main() {
        return 0;
    }