What are forward declarations in C++?

At: http://www.learncpp.com/cpp-tutorial/19-header-files/

The following is mentioned:

add.cpp:

int add(int x, int y)
{
    return x + y;
}

main.cpp:

#include <iostream>

int add(int x, int y); // forward declaration using function prototype

int main()
{
    using namespace std;
    cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
    return 0;
}

We used a forward declaration so that the compiler would know what “add” was when compiling main.cpp. As previously mentioned, writing forward declarations for every function you want to use that lives in another file can get tedious quickly.

Can you explain “forward declaration” further? What is the problem if we use it in the main() function?

8 Answers
8

Leave a Comment