Class Declaration Help

Hello cplusplus.com, this site was very useful for me and I'm new to the forums so... there's my breif intro.

Anyway, I am (trying) to make a game and have encountered an issue that I can't find a solution for. A class uses another class, that also uses that same class...
I'll make a code example below so it makes more sense.

1
2
class A{B var;};
class B{A var;};


That won't work, so I guess I need some way to declare the class B before class A is declared...

Thanks for help in advance.
Last edited on
closed account (L6b7X9L8)
I think you have to forward declare the class, something like:

1
2
3
4
class B;

class A{B var:}
class B{A var;}
Yes, that was the first thing I tried to do.
When I try that though I get "error: field 'var' has incomplete type"
You can't do it.

If every A contains a B, and every B contains an A (which in turn contains another B and so on), where does it all end?

You could have one of them contain a pointer to the other, e.g.
1
2
3
4
class B; // Forward declaration

class A { B* var; }; // Fine, compiler knows that B exists (but doesn't need the size of B)
class B { A var; }; // Fine, we have the full definition of A 
Last edited on
Thanks for the help, works great now.
Last edited on
Topic archived. No new replies allowed.