Search code examples
c++structforward-declaration

Correct way to forward declare structs?


Let's suppose I want to declare structs A and B

struct A{
  B toB(){
    return B();
  }
};
struct B{
  A toA(){
    return A();
  }
};

I'll get an error that type B is undefined

main.cpp:2:2: error: unknown type name 'B'

What is the correct way to forward-declare B?

Doing the following

struct B;

struct A{
  B toB(){
    return B();
  }
};
struct B{
  A toA(){
    return A();
  }
};

results in

main.cpp:4:4: error: incomplete result type 'B' in function definition
main.cpp:1:8: note: forward declaration of 'B'
main.cpp:5:10: error: invalid use of incomplete type 'B'
main.cpp:1:8: note: forward declaration of 'B'

Solution

  • The issue isn't with the forward declaration, the issue is that you're trying to use a B before its definition. A forward declaration only tells the compiler that there is, in your case, a struct named B, it doesn't define it.

    You can separate the definition of the method from the class, like so:

    struct B;
    
    struct A{
      B toB(); // B is not defined yet
    };
    
    struct B{
      A toA(){
        return A();
      }
    };
    
    
    B A::toB() { // Now that B is defined, you can use it
        return B();
    }