Re: Question now on .h vs forward declaration
"Stick" <Stick@discussions.microsoft.com> wrote in message
"John Carson" wrote:
You should *never* have mutual inclusion by design, because it is
impossible to have it work.
Your design should have only a one-way dependence of .h files. If
the .h file that is read first (because #included by the other file)
needs a class name from the .h file that is read second, then you
must handle that with a forward declaration of that class name.
Ok, I get what you are saying, and was able to fix everything and it
works wonderfully, but I'm still a little unsure what I am doing.
Specifically, I am now unsure when to #include vs. use a forward
declaration, as I thought that this was, in effect, what a .h
supposed to do.
Normally, for each class I put the class declaration in it's own .h.
So, if class B uses (sic) class A, then class B would #include the
class A .h file.
That is the normal approach for normal circumstances.
But now I'm thinking that I should do this only if class B "has a"
class A (or "is a" since it would be required for inheritance too).
So, in my previous problem, the Radiopage class did not "have a",
Cdu, and hence I should use forward declaration.
Also, I figured out that although my RadioPage class "has a" CduLine
class, I must put the #include "RadioPage.h" in the CduLine.cpp file,
or it will get included in other places where my intention is really
to just forward declare the CduLine class.
So, I think now in retrospect that my problem was I was putting other
.h files in #includes that did not really belong there.
Am I getting it?
Basic rule of thumb is to #include a .h file in any file that needs to see a
declaration that the .h file contains. Forward declarations are normally
restricted to those cases where you have no choice but to use them, i.e.,
cases of mutual dependence where class A refers to class B and class B
refers to class A.
You can use forward declarations more generally for those cases where a
class declaration only contains pointers or references to another class and
therefore does not need to see the whole class declaration. However, making
all those forward declarations can rapidly get tedious and most people only
use forward declarations when they have to. #including a .h file is simpler.