How to initialize a global variable prior to another?

M

mars

In my application, global variable A, during its construction, depends
on another global variable, say B. However, variable B may have not
been initialized by then. How can I make sure that variable B be
initialized before A? My compiler is Visual C++ 6.0. Thanks!
 
A

Axter

mars said:
In my application, global variable A, during its construction, depends
on another global variable, say B. However, variable B may have not
been initialized by then. How can I make sure that variable B be
initialized before A? My compiler is Visual C++ 6.0. Thanks!

You can declare variable B as a local static variable inside a global
function, and use the global function to access variable B.

FooB& GetVarB()
{
static FooB B;
return B;
}

When A needs variable be, it would call it via GetVarB
GetVarB().SomeFunction();

IAW C++ standard, this is garanteed to work durring construction,
because local static variable are garanteed to be constructed upon the
first call of the function.
For optimization, you could even inline this function, and declare it
in your header.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top