2
// I need to have access to 'a' in whole file
// I cannot call constructor now
static A a;

int main()
{
    /*
        some code
    */

    glewInit();

    /*
        some more code
    */

    a = A(); 
}

I need to call constructor after calling glewInit() function
It`s constructor is using gl functions

Can I prevent C++ from initialising 'a' variable, and if so, how?

krzysztof1222
  • 31
  • 1
  • 4

2 Answers2

5

Use function with a static variable:

A &getA() 
{
    static A a;
    return a;
}

and access it only when it can be created.

Slava
  • 43,454
  • 1
  • 47
  • 90
0

Slava's answer is great if the creation depends only on global state, but if you need to calculate some constructor parameters, the best thing to do is combine a local variable (since it's in main() it will survive to the end of the program) and a pointer to it:

static A* a;

int main()
{
    /* some code that determines arg1 and arg2 */

    A real_a(arg1, arg2);
    a = &real_a;

    /* call all the functions that use ::a */
}
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720