I am working on a project that works with linked lists. I was running into some issues that I eventually traced back to the fact that I had circularly placed #include
statements (ie. header file 1 has an includes header file 2 and header file 2 includes header file 1). This led me to the question of when do you actually need to use #include
? Do you use it if you want to use the class it defines? Can you access a class without including its header file if you include another header file that does include it? (ie. you have a class named Car
that includes the class Engine
, can you access the Engine
class from any file that includes Car.h
?).
The current project I am working on has produced many errors related to certain files not being able to access certain parts of a class that I thought was available to it and I haven’t been able to find a post on Stack Overflow that fully answers these questions.
5
You need to use an #include
when it defines something that you need the full declaration of. For example, when you need to create an instance of a type, or when you need to access members of an object, etc.
In some cases, you don’t actually need the full declaration, such as when simply defining a pointer/reference to an object, in which case you can get away with using a forward declaration instead (which you usually have to use to fix circular references between objects).
In your example, if Car.h
defines the Car
class with an Engine*
or Engine&
data member, then Car.h
could use a forward declaration of the Engine
class without #include
‘ing the Engine.h
header. Any unit that then wants to access the features of a car’s Engine
can #include
the Engine.h
header for themselves. A Car
doesn’t need to know what an Engine
looks like to know that it has an Engine
.