0

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'
2
  • 5
    This forward declaration is fine, this has nothing to do with forward declarations. Unlike Java or C#, in C++ one does not have to define class constructors and class methods inline. The definition of the actual constructor can be moved to after both classes are defined, resolving the issue with the incomplete type. Commented Jan 3, 2024 at 14:24
  • this answer on the dupe target shows how to split this up into pieces that can be stitched together when compiling. Commented Jan 3, 2024 at 14:27

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.