Forward declarations allow statically-typed programs to indicate the type and name of a symbol without actually defining it.
Forward declarations are how references to an undefined symbol can be avoided in a statically-typed language. Forward declarations allows the compiler to know the name and type of a symbol without the program defining it previously.
However, forward declarations (when declaring struct
s and class
es) are incomplete, which places special restrictions on what can and cannot be done with a forward declared type.
For example, consider the following case (C++):
class Parent
{
// ...
vector<Child> children;
};
class Child
{
// ...
Parent *parent;
};
When the compiler compiles the definition of parent, it finds a reference to the type Child
, which is undefined, causing the compilation to fail.
A forward declaration alleviates this issue:
class Child;
class Parent
{
// ...
vector<Child> children;
};
class Child
{
// ...
Parent *parent;
};
When the forward declaration is added, the compiler is aware that there will be a Child
class somewhere later in the program, and compiles successfully.