0

I have a class in

Game.h:

class Game 
{
public:

    ~Game (){}

    bool init(const char* title,int xpos, int ypos, int width, int height,bool fullscreen );


    void render();
    void update() ;
    void handleEvents();
    void clean();
    void draw();
    static Game* Instance();
    // a function to acces the private running variable 
    bool running () {return m_bRunning; }

private:
    Game ();
    static Game* s_pInstance;
    SDL_Window* m_pWindow;
    SDL_Renderer* m_pRenderer;
    bool m_bRunning;
    int m_currentFrame;

};

//create the typedef
typedef Game TheGame; 

and also in Game.cpp I have a static variable initialization like the following

Game* Game::s_pInstance = 0; 

So I intend to know why I need to use (Game*) variable type in here and is it a must?

JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • 1
    Yes. Also the typedef is not required - it serves no purpose. – cup Sep 02 '20 at 05:14
  • Unrelated: You may find the [Meyers Singleton](https://stackoverflow.com/a/1008289/4581301) a bit more convenient (and as of C++ 11 safer) – user4581301 Sep 02 '20 at 05:16

1 Answers1

4

I have a static variable initialization like the following

Game* Game::s_pInstance = 0;

This description is incomplete. More accurate: you have a static variable definition, and an initialization is part of this definition. The initialization does not need to mention the type, but the definition does. Syntactically, you could leave off the initialization part (drop = 0), but you would still need the definition in order to use the variable. Caveat: don't really drop the initialization except as an experiment to see that this compiles.

The definition needs to include the type of the thing being defined. That's the way the language works. On a more technical level, the presence of the type probably helps identify the line as a definition instead of an expression.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • So you are saying I don't need to explicitly use Game* for the initialization part but it would be a good practice to add that as it makes the code lot clearer to understand – rudra sarkar Sep 02 '20 at 05:32
  • @rudrasarkar No you misunderstood. `Game*` is required here. `Game*` is part of the definition, the initialisation is `= 0`. – john Sep 02 '20 at 05:36
  • 1
    @rudrasarkar As well as answering your question JaMiT was correcting your terminology. As stated what you have there is fundamentally a definition, and a definition requires a type. – john Sep 02 '20 at 05:39