Correct way to forward declare structs?

91 views Asked by At

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'
1

There are 1 answers

0
ChrisMM On BEST ANSWER

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();
}