Including a header vs forward declaring a class

Hi,

I need some clarification regarding the title statement. Suppose I have a project with multiple classes.

If class A has a member variable of class B, will I have to include b.h in a.h or will forward declaring class B in a.h suffice?

I'm actually confused when to forward declare a class and when to include a header file.

If someone can explain or provide any good links where I can study this, I'll be very grateful.

Thanks!
With a forward declaration about all you can do is have a pointer or reference to that class. If you are going use the class (create an object, call a member function, access one of it's variables, etc.) then you need to include the full class definition.

My advice is to always forward declare if it's enough and only include when you have to. THat way you are less likely to run into problems with circular dependencies.
Ok, Thanks Peter87. That was very helpful! Now I understand.
A few more basic questions:

How does a compiler interpret a forward declared class? I know that if I include a header, it is as good as writing the entire code contained in the header file.

What do we tell the compiler by forward declaring a class? Is it that "I promise you such a class exists in the project and you will surely find it when you compile that particular file that has it"?

Also, while creating a Makefile for a project that has forward declarations, do we have to specify the sequence in which files have to be compiled? In other words is it necessary that the file that contains the class declaration is compiled before the file that has forward declaration of that class?

Sorry for so many questions :)

Thanks
Topic archived. No new replies allowed.