3 ms·
You can only do that when using pointers or references: class B; class A { B* b; } class B { A* a; } because the compiler can
by ygra 10y ago
You can only do that when using pointers or references:
class B;
class A {
B* b;
}
class B {
A* a;
}
because the compiler can (obviously) not tell how large the instances of the other class are when you have a field of that type. Remember that the class layout has to be fixed at compile time and both instance sizes depend on one another. That's not solvable.
C# does the same, actually:
struct A {
B b;
}
struct B {
A a;
}
will cause the following error:
test.cs(2,5): error CS0523: Struct member 'A.b' of type 'B' causes a cycle in the struct layout
test.cs(6,5): error CS0523: Struct member 'B.a' of type 'A' causes a cycle in the struct layout
with classes and references it works, of course:
class A {
B b;
}
class B {
A a;
}
- Ygg2 10y agoThis is also what I attempted, and as I remember it didn't work either, though to be honest I was really worn out fighting the obscure compiler errors by that point, I might have missed a sigil somewhere. I spent good solid 30min trying to understand why defining and not defining my constructor was causing issues, to realize that the constructor error was actually a previous error, somewhere above the constructor. Rust, also notes where and how you created an infinite loop.
- netheril96 10y agoYour compile error is likely because you use references instead of pointers. Reference as a class member is really hard to get right because it can be initialized only once, and cannot be copied or moved.