Difference between "Class X" and "Include <X.h>"

I see in many programs if I have to include a class X, I can do it either by declaring "Class X" or "#include <X.h>" in the beginning of my program.
What is the difference between two and which is the preferred method?
Declaring "Class X" doesn't actually include it if the corresponding header is not included.

Declaring "class X" is a forward declaration. It's often used when you need to need to resolve a reference before it can be defined. However, that doesn't mean it is defined. You still need to include the header file.
It depends of a project design. If Class X is used in several modules it is better to place its definition in a header file and then include it in each module that uses the class. If only one module uses the class then you can define the class in that module.
class X; This is a forward declaration. It just says there is a class named X but there is no information on what it contains or how big, so you can't actually create any objects of X or call X's member functions or anything. The only thing you can do is to declare pointers and references to X.

#include <X.h> This includes X.h header file. You would get the same result by just copy paste the content of X.h instead of writing #include <X.h> , but don't do that. X.h probably contains the definition of class X so that will allow you to use class X as usual.

Prefer forward declaration whenever possible. Advantages are faster compilation times and less risk to run into problems with circular dependencies.
As they have all stated, you'd want to use the line class X; if your current class uses an object of X of a specific part of the class during compile time, so you would want it to make sure it knows what Class X is before it starts looking at the current class.
Topic archived. No new replies allowed.