Loading lessons...
Forward Declarations
Forward Declarations
C++ compiles from top to bottom: before you can call a function, the compiler must know that it exists. The forward declaration tells the compiler a function's signature before it sees the body.
Why it exists
Without a declaration, the compiler rejects a call to a function it has never heard of. When the body appears later in the file, a call made earlier fails:
int main() {
return add(1, 2); // ERROR: add is not yet declared
}
int add(int x, int y) { return x + y; }
Declaration plus definition
Fix it by adding a forward declaration at the top - the return type, name, and parameters with a semicolon but no body:
int add(int x, int y); // forward declaration (prototype)
int main() {
return add(1, 2); // now add is known
}
int add(int x, int y) { // definition
return x + y;
}
- The declaration promises: "a function add(int,int) returning int exists somewhere".
- The body can appear later in the file (or even in another file).
- Now main can call it freely.
The definition also works as a declaration
Writing the full function body implicitly declares the function too. You only need a standalone forward declaration when the definition isn't visible before the first call.
Prototypes in headers
Forward declarations are what header files (.h) hold. A header lists the function prototypes so any file that includes it can call those functions - you'll use this in the next lesson on multiple files.
TL;DR
- A forward declaration is a signature with a semicolon, placed before the first call.
- It lets you call functions that are defined later in the file.
- Example:
int add(int x, int y);. - A definition is also a declaration.
- Headers are built out of prototype-like declarations.