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.

// Forward Declaration of the sum()
void sum(int, int);
 
// Usage of the sum
void sum(int a, int b)
{
    // Body
}

Links

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:

class A {
	B* myB;
}
class B {
	A* myA;
}

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

class A;
class B {   
	A* myA;
}
 
// Or 
class B {
	class A;
	A* myA;
}
  • You would use B::A::function() if A is a nested class inside of B
  • Note that you would need to #include "A.h" if you want to use the methods of A

NOTE: Below doesn’t work, even if you did forward declaration. You cannot have two classes that fully contain objects of the other type.

class A {
	B myB;
}
class B {
	A myA;
}
  • 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.