Home > Blockchain >  field 'obj' has incomplete type note: forward declaration of 'class B'
field 'obj' has incomplete type note: forward declaration of 'class B'

Time:10-04

I have seen before in stack overflow classes can friend each other. Here I am doing class A and class B friend each other. But when I create an object in A class for B its throws an error which is "field 'obj' has incomplete type note: forward declaration of 'class B'". I also declared class B with forward declaration. But it's not working.

How can I solve it? Thanks for your Help!

#include<iostream>
class B;
class A{
    friend class B;
    B obj;
    public:
        int x = 199;
        
};

class B{
    friend class A;
    A obj;

};

int main(){
   
}

CodePudding user response:

If you had said B * obj;, it would work. The problem is that, without having the full declaration before hand, the compiler does not know how large B is, and thus cannot establish a size for A.

  • Related