In C++, unlike Java, When you write:
Game instance; // that should be the Instance
you are creating an actual object of type Game
. In Java this would be creating a handle variable and you would then need to use the new
operator to actually create the Game
object. That is not the way it works in C++.
In the source lines:
Game()
{
instance = this; // here I got the error.
}
the variable this
is actually a pointer to the current object. However instance
is not a pointer variable, which would be defined by Game *instance;
but rather is an actual Game
object. Assigning a pointer value to something that is not a pointer is a compile error.
One modification to your source, which may or may not be what you actually want, is to do the following changes:
#include <iostream>
#include "Game.h"
#include <string>
Game *instance; // global that contains a pointer to a Game object, no object created.
class Game
{
public:
Game()
{
instance = this; // we are creating an object of class Game now assign it to our global.
}
}
However this doesn't really make sense in C++. The constructor may be called more than once for multiple Game
objects.
Assuming that the header file Game.h contains the class definition, if you are wanting to just create a single instance of Game
then the most straightforward would be to write it as:
#include <iostream>
#include "Game.h"
#include <string>
Game instance; // the global Game object that is created as part of the application starting up.
However if you are wanting to create a single instance using the singleton design pattern which will enforce that there is one and only one such object created, you will need to do additional work which will require a more involved knowledge of C++ and class construction.