Forward Declaration

Learn what Forward Declaration are

Declaration vs Definition

In C++ you can declare a variable without defining it. Or you can declare and define a variable at the same time. A variable here can be anything : a variable, a function, a class etc.

When you Declare a variable in your program, you are simply saying that the variable exist. But what is its value ? nobody knows.

When you Define a variable, your are giving a certain value to that variable.

//I declare a function
float surf(float w, float h);

//I define the function later
float surf(float w, float h)
{
	return w * h;
}

//Or I declare and define the function in one time 
//I know, looks the same with the definition, that's because a definition create a declaration if none exits before
//The real difference happens in the computer memory, but I won't go into the details
float surf(float w, float h)
{
	return w * h;
}

//I declare a class
class my_class;

//I define the class later
class my_class
{
	my_class
}

//Or I declare and define the class in one time
//again, looks the same with the definition, but the difference is at the memory level
class my_class
{
	my_class
}

What Is A Forward Declaration

In the code below, I want to use the class NewScene inside the main function. But since I have defined the class after the main function, I cannot do that. In C++ the code is executed in order line by line. Since the class NewScene is defined after the main function the class simply do not exist when the main function is executed.

#include <Nero/engine/DevEngine.h>

int main()
{
	nero_log("hello world");

    nero::DevEngine engine(1305);
        engine.addScene<NewScene>("new scene"); //I cannot do that, NewScene does not exist
    engine.run();

    return 0;
}

//Scene class
class NewScene : public nero::Scene
{
    public:
        NewScene(nero::Scene::Context context): nero::Scene(context)
        {
            //Ctr
        }
};

In order to solve that problem, I just need a way to tell the compiler that the class NewScene exist, even if nobody knows what it looks like. The way you do is simply declare the class before the main function. By doing that I just did a Forward Declaration.

#include <Nero/engine/DevEngine.h>

//Forward declaration
class NewScene;

int main()
{
	nero_log("hello world");

    nero::DevEngine engine(1305);
        engine.addScene<NewScene>("new scene"); //I can do that, NewScene now exist 
    engine.run();

    return 0;
}

//Scene class
class NewScene : public nero::Scene
{
    public:
        NewScene(nero::Scene::Context context): nero::Scene(context)
        {
            //Ctr
        }
};

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Nero Games will use the information you provide on this form to be in touch with you and to provide updates and marketing.