refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program).
👁 Image
Example:
// Forward Declaration of the sum()
void sum(int, int);
// Usage of the sum
void sum(int a, int b)
{
// Body
}
In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this.
Example:
// Forward Declaration class A
class A;
// Definition of class A
class A{
// Body
};
Let us understand the need for forward declaration
with an example.
Example 1:
Output:
Compile Errors :
prog.cpp:14:18: error: 'A' has not been declared
friend int sum(A, B);
^
Explanation: Here the compiler throws this error because, in class B, the object of class A is being used, which has no declaration till that line. Hence compiler couldn't find class A. So what if class A is written before class B? Let's find out in the next example.
Example 2:
Output:
Compile Errors :
prog.cpp:16:23: error: 'B' has not been declared
friend int sum(A, B);
^
Explanation: Here the compiler throws this error because, in class A, the object of class B is being used, which has no declaration till that line. Hence compiler couldn't find class B.
Now it is clear that any of the above codes wouldn't work, no matter in which order the classes are written. Hence this problem needs a .
Let us add the forward declaration to the above example and check the output again.
Example 3:
The program runs without any errors now. A
forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.