Skip to content

Latest commit

 

History

History
123 lines (73 loc) · 3.23 KB

CppForwardDeclaration.md

File metadata and controls

123 lines (73 loc) · 3.23 KB

 

 

 

 

 

 

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:

 

 

For a list of VCL forward declarations, go to the VCL forward declaration page.

 

 

 

 

 

Example

 

This example shows the header file of a class before and after using as much forward declarations as possible.

 

Before

 


#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

 

 

 

 

After

 


#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

 

 

 

 

 

 

  1. Herb Sutter. Exceptional C++. ISBN: 0-201-61562-2. Item 26: 'Never #include a header when a forward declaration will suffice'