Initialized Engine as a static variable, is it a good practice?

Initialized Engine as a static variable, is it a good practice?
Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Engine {

    OpenGLSTUFF _openglstuff;

public:

    void renderSomething();

};

static Engine initialized_engine;

//returns initialized_engine;
Engine &getEngine();

//initializes initialized_engine variable.
void initEngine();

int main() {

    initEngine();

    //so that i can do this
    Object ball(30);
    //without doing this
    //Object ball(&engine, 30);

    return 0;
}

Last edited on
Cant say whether or not its considered good practice

but i think a better way to do it would be this:

1
2
3
4
5
6
7
8
9
10
11
int main() 
{

    Engine* engine = new Engine(); //Constructor initializes whatever needs to be initialized

    //Ball is derived from object
    Ball* ball = engine->CreateObject<Ball>(30); //engine creates & initializes object (which may include setting a reference to itself in the object), stores it, and returns a reference

    delete engine; //engine is cleaned up which in turn cleans up all the objects
    return 0;
}
Last edited on
if you have multiple engine objects and only want to initialize the graphics engine / hardware stuff once, you can do it with static as you did.


That said, I think you should also listen to Stav, or consider: the engine class may be better to keep apart from anything else. It should probably not draw anything or DO anything graphical, just handle the engine state and provide access to it. It may even be doable more cleanly as a singleton pattern if you follow this approach.

The drawn stuff can have its own classes.

Last edited on
> Initialized Engine as a static variable, is it a good practice?

If the Engine object is a singleton (as it appears to be) and has a non-trivial constructor, a Meyers' singleton will avoid the static initialisation order fiasco. https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use

Something like this:
1
2
3
4
5
6
Engine& getEngine()
{
    static engine the_engine ;

    return the_engine ; 
}

Topic archived. No new replies allowed.