title: Errors using forward declaration in c++
body: <p>I am trying to write a simple program in c++ where I have 2 classes, and both can access functions from each other.  This is a simplification of what I am actually trying to do in the end, which is to create a game with board and piece classes.  I was able to do this in java, but I am now running into problems trying to do the same in c++.  My code is as follows:</p>
  
  <pre><code>#include &lt;iostream&gt;
  class B;
  class A {
      public:
              void sync(B obj){
                      b = obj;
              }
              void print(){
                      std::cout &lt;&lt; "Hello from class A" &lt;&lt; std::endl;
              }
              void printBoth(){
                      std::cout &lt;&lt; "Hello from class A" &lt;&lt; std::endl;
                      b.print();
              }
      private:
              B b;
  };
  
  class B {
      public:
              B(A obj){
                      a = obj;
              }
              void print(){
                      std::cout &lt;&lt; "Hello from class B" &lt;&lt; std::endl;
              }
              void printBoth(){
                      std::cout &lt;&lt; "Hello from class B" &lt;&lt; std::endl;
                      a.print();
              }
      private:
              A a;
  };
  
  int main(){
      A a;
      B b(a);
      a.sync(b);
      a.printBoth();
      std::cout &lt;&lt; std::endl;
      b.printBoth();
      return 0;
  }
  </code></pre>
  
  <p>When I try to compile this with <code>g++ example.cpp</code>, I receive 5 errors:</p>
  
  <pre><code>example.cpp:20:5: error: field ‘b’ has incomplete type
  B b;
   ^
  example.cpp: In member function ‘void A::sync(B)’:
  example.cpp:7:8: error: ‘obj’ has incomplete type
  void sync(B obj){
      ^
  example.cpp:3:7: error: forward declaration of ‘class B’
  class B;
     ^
  example.cpp:8:4: error: ‘b’ was not declared in this scope
  b = obj;
  ^
  example.cpp: In member function ‘void A::printBoth()’:
  example.cpp:17:4: error: ‘b’ was not declared in this scope
  b.print();
  ^
  </code></pre>
  
  <p>I have never used forward declaration with classes, so I apologize if I am missing something glaringly obvious.  Any help is appreciated, and I thank you in advance.</p>