A forward declaration is the declaration of a data type the compiler will encounter further on. Because this lets the compiler check less code, forward declarations speed up compilation.
Never #include a header file when a forward declaration will suffice [1].
A forward declaration of a class can be used when nothing needs to be known about that class:
- The member functions of the class are not called
- Only a reference to the class is used (all references occupy the same space in memory)
- Only a pointer to the class is used (all pointers occupy the same space in memory)
For a list of VCL forward declarations, go to the VCL forward declaration page.
This example shows the header file of a class before and after using as much forward declarations as possible.
#ifndef Unit1H #define Unit1H #include <iostream> #include "UnitX.h" #include "UnitY.h" #include "UnitZ.h" struct MyClass { MyClass(X &x) : m_x(x) {} X& m_x; Y* m_y; Z m_z; }; std::ostream& operator<<(std::ostream& os, const Unit1& y); #endif
#ifndef Unit1H #define Unit1H #include <iosfwd> struct X; struct Y; #include "UnitZ.h" struct MyClass { MyClass(X &x) : m_x(x) {} X& m_x; Y* m_y; Z m_z; }; std::ostream& operator<<(std::ostream& os, const Unit1& y); #endif
- Herb Sutter. Exceptional C++. ISBN: 0-201-61562-2. Item 26: 'Never #include a header when a forward declaration will suffice'