Forward reference in struct

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Oct 8 05:59:16 PDT 2007


Simen Haugen wrote:
> I've hit a problem with forward referencing. Is it possible to manually add 
> a forward reference, or isn't what I'm trying to do here allowed?
> 
> struct A {
>  B b;
> }
> 
> struct B {
>  union {
>   int i;
>   A a;
>  }
> }
> 
> 
> t.d(5): struct test.A unable to resolve forward reference in definition
> t.d(10): anonymous union unable to resolve forward reference in definition
> t.d(9): struct test.B unable to resolve forward reference in definition 

Let's disregard the int. You essentially have this:
-----
struct A {
     B b;
}
struct B {
     A a;
}
-----
Now ask yourself this question: How big is A?
Obviously, since it's a struct with 1 member, it's equal to the size of 
B. But how big is B? By the same reasoning, it's as big as A.
You have an infinite "member recursion", which isn't allowed.

To fix this, you may want to change A.b and/or B.a to a pointer, or 
change A and/or B from a struct to a class (since classes are always 
stored by reference, which is essentially an implicit pointer).


More information about the Digitalmars-d-learn mailing list