-3

As somebody without any formal training in programming, I'd like to know whether my C++ coding approach is considered good practice. Specifically, I am talking about the use of classes whose members are all static. This is a model which I use frequently, for cases when I know for certain that the class will only be instantiated once, and I want to be able to access that class from anywhere in my code. However, it tends to look a little odd because of the vast number of static keywords around, and the fact that I have to explicitly initialise these variables outside the class definition.

For example, if I am writing a game, there may be several classes which I instantiate just once and want to access from anywhere. These classes could be Graphics, to represent the colours and shapes to render, World, to represent the world in which my characters live, User, to represent the current human player of the game, Score, to represent the current score, etc. I would typically create these as "static" classes, because then I can access them from anywhere in my code. If they were "non-static" classes, then I would have to keep passing around pointers to these objects.

So, for a football game, my code might look like:

// world.h

class World
{
public:
  static float pitch_colour;
  static float pitch_size;
  static float player_colour;
  static float player_size;
  static int num_players;
  static std::vector<Player> players;

  static void UpdatePositions();
};



// world.cpp

float World::pitch_colour = 0.9;
float World::pitch_size = 100;
float World::player_colour = 0.3;
float World::player_size = 5;
int World::num_players = 10;
std::vector<Player> World::players = std::vector<Player>(World::num_players);

void World::UpdatePositions()
{
    for (int i = 0; i < num_players; i++)
    {
        players[i].UpdatePosition();
    }
}



// main.cpp

int main()
{
    while (true)
    {
        World::UpdatePositions();
        Graphics::DrawPitch(World::pitch_size, World::pitch_colour);
        for (int i = 0; i < World::num_players; i++)
        {
            Graphics::DrawPlayer(&World::players[i], World::player_size, World::player_colour);
        }
     }
 }

This kind of code runs fine, but I'm just wondering whether using lots of static classes like this is a typical approach, or whether there is something more highly recommended? Thanks!

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247

1 Answers1

1

If you just want to group global variables/functions (as you seem to actually be doing here) just put them inside a namespace.

OTOH, what you seem to be doing looks a lot like the singleton pattern, here you can find some suggestions and a ton of links/dupes:

C++ Singleton design pattern

Community
  • 1
  • 1
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299