1

I want to create two classes using each other. This is the code:

class B;
class A {
public:
    A(B* b) : b(b) {}
    void Foo() {
        b->data++;
    }
    B* b;
};

class B {
public:
    void Boo() {
        A a(this);
        a.Foo();
    }
    int data = 0;
};

int main()
{
    B b;
    b.Boo();
}

When I compile it in visual Studio 2015, I got the error:

error C2027: use of undefined type 'B'

which points to line six: b->data++;

I have read the problem here, but I have used forward declarations so A should know the existence of B. Also, I don't "have two classes directly contain objects of the other type" because only B contains A but A does not contain B; it uses a pointer to B. Also, my code doesn't seem essentially different from the answer here since there the World class contains objects of Agent and the two classes use each other. But my code just can't compile. So I think my issue is not duplicate. Could you please help me work around this mutual-use issue? Thanks a lot.

Community
  • 1
  • 1
user5280911
  • 723
  • 1
  • 8
  • 21
  • 1
    1) This has been asked _countless_ times before; please google it. 2) You need to [_declare_](http://www.cprogramming.com/declare_vs_define.html) `A::Foo()` before `B` and then [_define_](http://www.cprogramming.com/declare_vs_define.html) `A::Foo{}` after `B` has been defined. – Qix - MONICA WAS MISTREATED Apr 24 '17 at 01:11
  • @Qix: I have explained in detail at the end that I have read that problem, followed it but still got error. Have you read that? The problem IS DIFFEREENT. which is also shown from your comment. Why are you so captious? – user5280911 Apr 24 '17 at 01:18
  • You haven't completely used forward declarations, and you haven't read my comment thoroughly. You forward declared `class B;` but you declared _and_ defined `A::Foo` - at which point `B` hadn't been defined. You need to _declare_ (and _only declare_) `A::Foo`, define `B`, _then_ define `A::Foo`. – Qix - MONICA WAS MISTREATED Apr 24 '17 at 01:20
  • @Qix: That problem is not making forward declarations, but my problem is knowing forward declarations but not know how to make forward declarations correctly. Can you sense the difference? Can you find a duplicate question that pointing out correct forward declarations? It is you who "haven't read my comment thoroughly". – user5280911 Apr 24 '17 at 01:27

0 Answers0