Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an static instance of a Class in C++?

Some months ago I created a C# Project of a game called Vexed. Now I'm creating a Tetris, but in C++. Basically I want to use the same logic I used in the other project, it was a little bit like this:

I created a Class called "Game" where there was all the information about the game. It had it's methods, variables and everything. Then, I created a static class called "PublicInstances" or something like that, and in that class I declared something like this:

static class PublicInstances
{
    public static Game vexedGame = new Game(); //This is C# and works.
}

It made it so simple to use then, because any change I made on the game was saved in that static instance of my class and I could access it anywhere on the project. I want to know how to do exactly that with C++, to create a public or global instance of my class Game so I can access it and change it everywhere and have everything updated in any Form or class of my project. I would really appreciate your help.

// Sorry if my English isn't the best ^^

like image 563
avatarbobo Avatar asked Oct 02 '13 04:10

avatarbobo


People also ask

Can we create instance of static class?

The compiler will guarantee that instances of this class cannot be created. Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor.

How do we declare static class data?

- Static data members of a class are declared by preceding the member variable's declaration with the keyword static. Only one copy of static data members exist and all objects of the class share that variable. Unlike regular data members, individual copies of a static member variable are not made for each object.

Can we declare static variable in class?

Static variables in a class: As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of same static variables for different objects.

How do you make a class static?

We can declare a class static by using the static keyword. A class can be declared static only if it is a nested class. It does not require any reference of the outer class. The property of the static class is that it does not allows us to access the non-static members of the outer class.


1 Answers

Revisited and summarised

Option 1

You may simply declare and define a global instance of Game object. In a header file, e.g. game.h:

extern Game globalGameObj;

When you include game.h in a source file globalGameObj name becomes visible. You also need to create an actual object. In a source file, e.g. game.cc (outside of any class):

Game globalGameObj;

Access it by the variable name:

globalGameObj.do_some_work();

Option 2

Use a pattern often called singleton. Add the following to your Game class (game.h):

class Game
{
  public:
    static Game &shared_instance() {static Game game; return game;}

  private:
    // Make constructor private. Only shared_instance() method will create an instance.
    Game() {/*whatever initialisation you need*/}
};

You access Game instance with shared_instance() method:

Game::shared_instance().do_some_work();

You do not use anything like your static class PublicInstances in the above. C++ allows you to introduce a namespace (e.g. PublicInstances) to provide name isolation and keep your global objects in one place but it'll probably to be an overkill. In any case if you have few global objects then it is likely to be a bad design.

What option is better? Some people would argue that singleton pattern should be used. It guarantees that only a single instance is created. However both option 1 and option 2 have the same problem: they introduce a global object in your code with all disadvantages attributed to global variables. I'd say that singleton is a global object in disguise. I do not see deciding technical reasons in favour of either option so I'd say that it is a matter of personal taste.

Historical note :)

My first suggestion for Option 2 was to use a dynamically allocated Game object rather than a function local static object.

static Game *instance() {if (!_inst) _inst = new Game(); return _inst;}

Few people suggested that it was not the best way anymore, thank you Kal, argiopeweb and Simple. C++03 has issues initialising static objects in presence of threads. C++11 guarantees safe initialisation of statics.

C++11 draft, secion 6.7

such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

like image 104
dmitri Avatar answered Sep 22 '22 13:09

dmitri