Forward Declaration
Seen in CS247.
A forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.
We use the interface file (.h
) file in C++ to make all the forward declarations.
Links
- https://www.geeksforgeeks.org/what-are-forward-declarations-in-c/
- https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c
Question: Is forward declaration REALLY needed?
Beyond the fact that forward declaration helps with cleaner code and minimizes recompilation (see Header File for reason), in cases of circular dependencies, one absolutely needs to forward declare.
This example is from the Preprocessor note:
The issue is that each class needs to know the other exists before it can be created.
Forward declarations can break these circular dependencies. You would do something like
- You would use
B::A::function()
ifA
is a nested class inside ofB
- Note that you would need to
#include "A.h"
if you want to use the methods ofA
NOTE: Below doesn’t work, even if you did forward declaration. You cannot have two classes that fully contain objects of the other type.
- A contains B, and B contains A, which contains B, which contains A… (infinite recursion)
Use two classes where each has a pointer or reference to an instance of the other class.