Why do I need to use forward declarations for a class when I am already including the relevant header file? It has fixed my problem but confused me!
essentially class A needs to know about class B and visa-versa. I was getting the error “sytax error – identifier” before I included the forward declarations. I was under the impression including a header file essentially meant you WERE declaring the other class where you put #include.
When you have a circular include dependency, and you’re properly using include guards (as you clearly are), then since there isn’t an infinite circular include, the compiler has to stop at some point, and it doesn’t know about the contents of the other header. When you add the forward declaration it’s able to compile your code.
For example,
AincludesB. ThenBincludesA, butA‘ include guard kicks in and prevents it from being evaluated a second time. Then it drops back intoBwhich doesn’t know about anything fromA.hat that point because the include guard prevented its inclusion. The forward declaration however doesn’t have any include guards around it so it proceeds as normal.There’s nothing inherently wrong with circular dependencies, but I do always suggest taking a second look at your design to see if factoring out logic into a third class is possible. Forward declarations are the C++ mechanism to prevent infinitely circular dependencies.