Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - forward declarations

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, A includes B. Then B includes A, but A' include guard kicks in and prevents it from being evaluated a second time. Then it drops back into B which doesn't know about anything from A.h at 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...