forward declaration..

hello friends,
i am new to C++ i have a question,
say i have 2 classes in 2 files (in same directory) say... A.cpp A.h and B.cpp B.h
in B.cpp's public i.e. (Class B's public) i want to have an instance of Class A say A *test;
Now, my question is whether it is sufficient to include the file A.h in B.h ? or i also need to say Class A (as a forward declaration in B.h) in B.h ?
When to use the forward declaration ? when is it necessary ? is there any specific conditions ?
Thanks in Advance..

Now, my question is whether it is sufficient to include the file A.h in B.h or i also need to say Class A (as a forward declaration in B.h) in B.h ?

Click to expand...

If you just need to use a pointer to A like A *test, then you should use forward declaration of A. Of course including A.h will also do the job, but will make the compilation process slower. If Class B inherits from A (implicitly or explicitly), then including A.h is a must.

Yes, there are. When you forward declare, the compiler has no idea about the contents of the class, it just knows that a class exists. So, you cannot use forward declaration for a class, when you want to access the members of that class.

Some examples, for further clarification. When you forward declare a class A, you can do things like:

Declaring a reference or pointer to it.

Declaring a func, whose arg type or return type is that class.

Declaring a func, whose arg type or return type is pointer/reference to that class.

but i have one more question.. because i have a situation here.. where even though i include .h file and if i try to compile the code without forward declaration , the compiler throws error saying ISO C++ forbids something (at the line where i use a A *test)
So, even though i include A.h why cant the compiler find that there is a class named A, What makes the compiler to throw error ?